paramiko模块(远程操作服务器)
django+paramkio实现远程某些服务器执行命令+上传文件
用于帮助开发者通过代码远程连接服务器,并对服务器进行操作。
pip3 install paramiko
-
远程执行命令【用户名和密码】
import paramiko # 创建SSH对象 ssh = paramiko.SSHClient() # 允许连接不在know_hosts文件中的主机 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接服务器 ssh.connect(hostname='192.168.16.85', port=22, username='root', password='123456') # 执行命令 stdin, stdout, stderr = ssh.exec_command('df') # 获取命令结果 result = stdout.read() # 关闭连接 ssh.close() print(result.decode('utf-8'))
-
远程执行命令【公钥和私钥】(公钥必须提前上传到服务器)
import paramiko private_key = paramiko.RSAKey.from_private_key_file(r'C:/Users/Administrator/.ssh/id_rsa') # 创建SSH对象 ssh = paramiko.SSHClient() # 允许连接不在know_hosts文件中的主机 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接服务器 ssh.connect(hostname='192.168.16.85', port=22, username='root', pkey=private_key) # 执行命令 stdin, stdout, stderr = ssh.exec_command('df') # 获取命令结果 result = stdout.read() # 关闭连接 ssh.close() print(result)
-
远程上传和下载文件【用户名和密码】
import paramiko transport = paramiko.Transport(('192.168.16.85', 22)) transport.connect(username='root', password='123456') sftp = paramiko.SFTPClient.from_transport(transport) # 将location.py 上传至服务器 /tmp/test.py # sftp.put('wy.txt', '/data/wy.txt') sftp.get('/data/wy.txt', 'xx.txt') transport.close()
-
远程上传和下载文件【公钥和私钥】
import paramiko private_key = paramiko.RSAKey.from_private_key_file(r'C:/Users/Administrator/.ssh/id_rsa') transport = paramiko.Transport(('192.168.16.85', 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()
补充:通过私钥字符串也可以连接远程服务器。
key = """-----BEGIN RSA PRIVATE KEY-----
MIIG5AIBAAKCAYEAu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HNylriVRb+hjXR3LBk8tyMAqR4rZDxfBNfPip5en
4TBMg8UATf43dVm7nv4PM2e24CRCWXMXYl7G3lFsQF/g7JNUoyr6bZQBf3pQcBw4
IJ38IcKV+L475tP4rfDrqyJz7mcJ+90a+ai5cSr9XoZqviAqNdhvBq5LjGOLkcdN
bS0NAVVoGqjqIY/tOd2NMTEF6kVoYfJ7ZJtjxk/R3sdbdtajV3YsAg==
-----END RSA PRIVATE KEY-----"""
import paramiko
from io import StringIO
private_key = paramiko.RSAKey(file_obj=StringIO(key))
# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='192.168.16.85', port=22, username='root', pkey=private_key)
# 执行命令
stdin, stdout, stderr = ssh.exec_command('df')
# 获取命令结果
result = stdout.read()
# 关闭连接
ssh.close()
print(result)
基于xshell连接服务器
-
用户名和密码
-
公钥和私钥(rsa)
-
生成公钥和私钥
ssh-keygen.exe -m pem 在当前用户家目录会生成: .ssh/id_rsa.pub .ssh/id_rsa
-
把公钥放到服务器
ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.16.85
-
以后再连接服务器时,不需要在输入密码
ssh root@192.168.16.85
-