Python-Paramiko项目实战(一)
远程执行命令
iimport os
import paramiko
def client_ssh_conn(host_name,passwd,command):
#创建sshclient
clint = paramiko.SSHClient()
#自动添加密钥到know_hosts文件
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#连接服务器,填充账号和密码
client.connect(hostname=host_name,port=22,username=root,password=passwd)
#远程执行命令
stdin, stdout, stderr = client.exec_command('command')
#获取命令结果
print (stdout.read().decode('utf-8'))
#关闭连接
client.close()
#打开文件
with open("/opt/python/host_list.txt",'r') as host_file:
#for循环读取
for host in host_file:
data = host.strip('\n')
#传入参数
host_name,passwd,command = data.split(',')
print (f'--------{host_name}--------')
#调用client_ssh_conn()
client_ssh_conn(host_name,passwd,command)
/opt/python/host_list.txt内容如下
192.168.1.1,password01,df -h
192.168.1.2,password02,date
192.168.1.3,password03,cat /etc/passwd
192.168.1.4,password04,cat /etc/hosts
192.168.1.5,password05,hostname

浙公网安备 33010602011771号