Paramiko模块
安装:
pip3 install paramiko
示例:
import paramiko
# 创建ssh对象
ssh = paramiko.SSHClient()
# 允许连接不在know_host文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='39.107.24.78',port=22,username='root',password='123456')
# 执行命令
stdin,stdout,stderr = ssh.exec_command('hostname')
# 获取命令结果
result = stdout.read()
# 关闭连接
ssh.close()
print(result.decode('utf-8'))
### 使用秘钥连接
# 获取私钥
private_key = paramiko.RSAKey.from_private_key_file(r'/Users/liuguixiang/.ssh/id_rsa')
ssh.connect(hostname='39.107.24.78',port=22,username='root',pkey=private_key)
import paramiko
from io import StringIO
#私钥
key = """
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAqSvjvRx9gljKOWe1vxwXAaL3wnw/0JIWZJz35g+3c8Sd3s43
vCQh4wqqx7CmglXk4zCvX5feqlnKIPQ98dWU/2Ng+VtkBab8foPE7b+efZ5Pc7XN
J3+Pjc67He2wnRjAaAJ6SjSfWLSH1wpxvOMn9tWnB0JJRFpnAW1p5Bzfy5kqRU70
Hmr8GswQgfxtdYcJ2jF8L5fEV8MqZAJ439QMs6Hz2tObTSuFd0FPVTqdSUb+r1Su
aO90+vrnqGpPgIG9hB/L2PP0KDvDg+MX7lgdfD7fLd9+AJ+uI8i+4iKmllGB6rNO
4NI3Be+S5HeiOeoXAxtH/q2YKuVgRC+NGY4zbQIDAQABAoIBAH+Njitave94DxH1
dn3gKiCbxf+oO12BqMy35dpbY1EwoHAMQM3k2H0Zx+bE9Oc06F28qZ6EHemHxfXO
8p3TEoL1ZXreQ65XV+30YJl6b3/7y6BNJaBwd8bOZxuLyizJKtnBdH9a6gKyK/Ih
99wZ0lo0gbnhaujU2PGkk8DhXIRfgA4qWCAkV9cSDVBwjYk6DIzggnXzjMMsuy43
MtWN8r42tPPqeq7bhSVlZarLkgOAAap9d33Pvf8EYiYTevcoLHjPiHhFxFr8qUYw
KakUv7g/aBj0npA0WjcjqvPe21IRS4LnlSRwccRCBmpQxWERj86r/KzqzHSMdr4v
zVRM5UECgYEA18+pP4uVgbgwawsJ2LsuBha/Hyc30G4h9Fe+t6yP22OAwQoyoQwe
-----END RSA PRIVATE KEY-----"""
# 创建ssh对象
ssh = paramiko.SSHClient()
# 允许连接不在know_host文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 获取私钥
private_key = paramiko.RSAKey(file_obj=StringIO(key))
# 连接服务器
ssh.connect(hostname='39.107.24.79',port=22,username='root',pkey=private_key)
# 执行命令
stdin,stdout,stderr = ssh.exec_command('hostname')
# 获取命令结果
result = stdout.read()
# 关闭连接
ssh.close()
print(result.decode('utf-8'))
示例二(上传下载文件):
import paramiko
transport = paramiko.Transport(('39.107.24.78',22))
transport.connect(username='root',password='123456')
sftp = paramiko.SFTPClient.from_transport(transport)
# 上传
sftp.put('a.txt','/data/a.txt')
# 下载
sftp.get('/data/a.txt','b.txt')
transport.close()
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。