文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

python paramiko使用

2023-01-31 01:58

关注

 http://www.lag.net/paramiko/

Working with paramiko

SSHClient is the main class provided by the paramkio module. It provides the basic interface you are going to want to use to instantiate [url=]server[/url] connections. The above code creates a new SSHClient object, and then calls ”connect()” to connect us to the local SSH server.
Here’s a simple example:

1
import paramiko

 

2
ssh = paramiko.SSHClient()


Another way is to use an SSH key:

1
import paramiko

 

2
import os

 

3
privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')
 

 

4
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)

 

5
ssh.connect('192.168.1.2', username = 'vinod', pkey = mykey)


注意:(这里的key,用的是RSAkey,linux下我们在用ssh-keygen -t rsa来指定它,windows下需要原始pem文件格式才可以在这里用,否则将会报无法识别的RSA KEY。类似如下
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAlL0Zti0UgsdpmOK1yA6WaIxrqOiWD3lz/8DBfWydI3YcBpJSv//vvH4KuduU
0Wic+lLwe9Yu7axsOCmWjIfmh35Rdj0+LNkhHtfybRGrRpZrEQ2wHrBUgMumLFVPIHEsv2zMbBkd
r2atRd4by+BS/4kBn1NaElTW8Tw5FlVUsk43dmh4q4wczMHcghsRxFXLj78LRew37iXLYfHBEKDA
n/F71rKuuTiPXLDGaCwq5o8tUa51p/TKRpm5caBI25i7pmLQUo7IY1vWShSdaif7Jq61jEU3EkJq
Jj8u9W7iYAYBPq/xw8tKE6i9EzD57ug7JDElulI2rphdIkuT9zj//wIDAQABAoIBACBGbGbgn1vF
g79+Km3v5GlpVw8+8RkIhMhRfmsF/48rWOeAJt6s3cusGg28fS13ouCa0L4+es5uJMmHFLkH4Fk0
at7aaTx4HTzBJUTPmbfmefMoYjg2kQ+loThrhpEGnewn4q/uP0fJYv4PNT7nPXtfsm9tOdVSfZW5
OLYE7C0IgQv0QLe7SkR6Vkz3Qi2gbmIaMu82pP5ugk1NA4OKIrkPJbzOEtkf3d8iblrU0baeYa6I
FWM42ChOzoITkN1jYJvudGjERa3/zRb80OEF6evz9SKHOxjy9jzgubdwQT9Crl3Zf90qv/ZGC1G3
6EmBy51xFMVEXAELd/6o8j6ENEkCgYEA0g5DGbAodqbLTp1Qf7FtE2t5WCYSzzwVNbQimLV1vOUG
tY3hVLywIpA1Kujf1dNOmTJVUuiBPPlcU/YjHMT9h33wRDc0oXmqx2++MF0aQtRy6U4iFRQJWs+v
d8J1eQ8jgEhQNZLWrqK6zue0jW6YFO2Wlz/GCOACbkp40FJysHUCgYEAtUV81BUTy07DAHfV+yIJ
kms5UGDle/lOTHzyhBmc2gRdoMm/jeGgL+ZGC0OespXaDewn8F/AP+2m+pLDfMEKYZ/VIrjICx0T
0BpxW9OPdUkuVMH5VwW6fNgsVh0jjwUZfLj0gUvSHSjsUUpomqG487uRkeklkLNANXqTi2YDYCMC
gYAC1IRc7T2uU5L7rSzve4F/uHv7DxBD0Ihsn8+zhQZgFCnh+lZl4ODypkTBHkAdzmoJsF7r7gwH
uUhgLTnN4m2UDMNW9/NylYQSidPjLO30po4hzJay+AEkQxYXI/yXM/gDe3XxMthHpBOmRALvwOS1
q3nS8d4GMpZ1y/USwXmgHQKBgDJAaTKCBVK/Kt/eWLud2/lzMBhQRE3x9vrNSI3Ga+0keLAyPaAf
hEDDHXfR7xSi5igl54yDftA6GagtN3RGL5KQtI1DnHE4Rl3Sdsp2A7cH6ogknfK569DgPKpCubDU
QRSKUX3mfwEGbzy52/XCD3vB68D/WSKcDpjEulJSnWzxAoGAB7oGwMMnwy2GSxAuPiiXOl4n5hwa
vJ15qCmKTSYx7eWCu1zCE3NYW6Pvohz+YRJqilAOt45uNK65g6w/ZbX/oh2lujDd3VU4INU4fKCS
FCkypPZFAxnG70tuo/US/4W34zOAxoALrIC0uOHyXD2P1yYcQgIkNp7VmoZ7FK/7LMs=
-----END RSA PRIVATE KEY-----



而且如果你的RSA Key有密码的话,你还需要
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile,password='12345678')




不过,我们可以用publickey来登录的。
解法如下:
serverHost = "127.0.0.1"
serverPort = 22
userName = "root"
keyFile = "~/.ssh/badboy"
known_host = "~/.ssh/known_hosts"
channel = paramiko.SSHClient();
channel.load_system_host_keys( known_host )
channel.connect( serverHost, serverPort,username = userName, key_filename = keyFile )



Running Simple Commands
Lets run some simple commands on a remote machine.

1
import paramiko
2
ssh = paramiko.SSHClient()

 

3
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())<=这样的话,就会报paramiko.SSHException: Unknown server

 

4
ssh.connect('beastie', username='vinod', password='secret')

 

5
stdin, stdout, stderr = ssh.exec_command('df -h')

 

6
print stdout.readlines()

 

7
ssh.close()


“paramiko.AutoAddPolicy()” which will auto-accept unknown keys.

Using sudo in running commands:

01
import paramiko


02

03
cmd = "sudo /etc/rc.d/apache2 restart"


04

05
ssh = paramiko.SSHClient()

 

06
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

 

07
ssh.connect('beastie', username='vinod', password='secret')

 

08
stdin, stdout, stderr = ssh.exec_command(cmd)

 

09
stdin.write('secret\n')

 

10
stdin.flush()

 

11
print stdout.readlines()

 

12
ssh.close()


在这个例子中,无法运行,也无法解释,希望志同道合的朋友能给个解释!



Secure File Transfer Using SFTPClient
SFTPClient is used to open an sftp session across an open ssh Transport and do remote file operations.
An SSH Transport attaches to a stream (usually a socket), negotiates an encrypted session, authenticates, and then creates stream tunnels, called[url=]Channel[/url]s, across the session. Multiple channels can be multiplexed across a single session (and often are, in the case of port forwardings).
以下是用密码认证功能登录的
#!/usr/bin/env python
import paramiko
socks=('127.0.0.1',22)
testssh=paramiko.Transport(socks)
testssh.connect(username='root',password='000000')
sftptest=paramiko.SFTPClient.from_transport(testssh)
remotepath="/tmp/a.log"
localpath="/tmp/c.log"
sftptest.put(remotepath,localpath)
sftptest.close()
testssh.close()

以下是用DSA认证登录的(PubkeyAuthentication)
#!/usr/bin/env python
import paramiko

serverHost = "192.168.1.172"
serverPort = 22
userName = "root"
keyFile = "/root/.ssh/zhuzhengjun"
known_host = "/root/.ssh/known_hosts"
channel = paramiko.SSHClient();
#host_keys = channel.load_system_host_keys(known_host)
channel.set_missing_host_key_policy(paramiko.AutoAddPolicy())
channel.connect(serverHost, serverPort,username=userName, key_filename=keyFile )
testssh=paramiko.Transport((serverHost,serverPort))
mykey = paramiko.DSSKey.from_private_key_file(keyFile,password='xyxyxy')
testssh.connect(username=userName,pkey=mykey)
sftptest=paramiko.SFTPClient.from_transport(testssh)
filepath='/tmp/e.log'
localpath='/tmp/a.log'
sftptest.put(localpath,filepath)
sftptest.close()
testssh.close()

以下是用RSA Key认证登录的
#!/usr/bin/evn python

import os
import paramiko

host='127.0.0.1'
port=22
testssh=paramiko.Transport((host,port))
privatekeyfile = os.path.expanduser('~/.ssh/badboy')
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile,password='000000')
username = 'root'
testssh.connect(username=username, pkey=mykey)
sftptest=paramiko.SFTPClient.from_transport(testssh)
filepath='/tmp/e.log'
localpath='/tmp/a.log'
sftptest.put(localpath,filepath)
sftptest.close()
testssh.close()

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯