paramiko模块

Paramiko模块

大安市网站制作公司哪家好,找成都创新互联!从网页设计、网站建设、微信开发、APP开发、成都响应式网站建设公司等网站项目制作,到程序开发,运营维护。成都创新互联2013年开创至今到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选成都创新互联

安装:

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()

文章名称:paramiko模块
文章源于:http://pwwzsj.com/article/gsedjd.html