一、安装 paramiko 模块
$ pip install paramiko
二、连接服务器执行命令
import threading,paramiko
url_list = ['192.168.88.130',
'192.168.88.131',
'192.168.88.132',
'192.168.88.133',
]
def private_key_connect(ssh_ip):
'''基于公钥连接
基于私钥字符串进行连接
from io import StringIO
key_file = open('/root/.ssh/id_rsa',r).read()
private_key = paramiko.RSAKey(file_obj=StringIO(key_file))
transport = paramiko.Transport((ssh_ip, 22))
transport.connect(username='root', pkey=private_key)
ssh = paramiko.SSHClient()
ssh._transport = transport
stdin,stdout,stderr = ssh.exec_command('uptime')
'''
private_key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=ssh_ip,port=22,username='root',password=private_key) #连接
stdin,stdout,stderr = ssh.exec_command('uptime') #执行命令
res,err = stdout.read(),stderr.read()
result = res if res else err
print(ssh_ip,result.decode())
ssh.close()
def user_passwd_connect(ssh_ip):
'''基于用户名和密码连接
SSHClient 封装 transport
transport = paramiko.Transport((ssh_ip, 22))
transport.connect(username='root', password='123456')
ssh = paramiko.SSHClient()
ssh._transport = transport
stdin,stdout,stderr = ssh.exec_command('uptime')
'''
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=ssh_ip,port=22,username='root',password='123456')
stdin,stdout,stderr = ssh.exec_command('uptime')
res,err = stdout.read(),stderr.read()
result = res if res else err
print(ssh_ip,result.decode())
ssh.close()
if __name__ == '__main__':
for ip in url_list:
t = threading.Thread(target=private_key_connect,args=(ip,))
# t = threading.Thread(target=user_passwd_connect,args=(ip,))
t.start()
三、上传和下载文件
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import paramiko
url_list = ['192.168.88.130',
'192.168.88.131',
'192.168.88.132',
'192.168.88.133',
]
def user_passwd_upload_wget(ssh_ip):
'''基于用户名和密码上传下载文件'''
transport = paramiko.Transport((ssh_ip, 22))
transport.connect(username='root', password='123456')
sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')
transport.close()
def private_key_upload_wget(ssh_ip):
'''基于密钥上传下载文件'''
private_key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
transport = paramiko.Transport((ssh_ip, 22))
transport.connect(username='root', pkey=private_key)
sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')
transport.close()
if __name__ == '__main__':
for ip in url_list:
user_passwd_upload_wget(ip)
# private_key_upload_wget(ip)