Paramiko是SSHv2协议的Python(2.7, 3.4+)实现,提供客户机和服务器功能。虽然Paramiko利用Python C扩展实现了低级加密,但它本身是一个围绕SSH网络概念的纯Python接口,我们可以通过官网获取更多它的信息。其用法和API文档可以在我们的代码文档站点上找到。
Paramiko主要是为了实现连接远程主机、SFTP传送文件等功能。
操作系统:rhel7.3
python版本:3.6
百度网盘下载链接:https://pan.baidu.com/s/1MNQrYV99dyyLjjhe-ubWBA 提取码: u25r
安装Paramiko需要先安装pycrypto模块!!!
[root@python ~]# wget http://ftp.dlitz.net/pub/dlitz/crypto/pycrypto/pycrypto-2.6.tar.gz
### 依赖,否则报错error: command 'gcc' failed with exit status 1
[root@python ~]# yum install -y python-devel
[root@python ~]# tar xf pycrypto-2.6.tar.gz
[root@python ~]# cd pycrypto-2.6/
[root@python pycrypto-2.6]# python setup.py build && python setup.py install
测试:
[root@python ~]# python
Python 3.6.0 (default, Nov 6 2018, 18:56:33)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import Crypto ###没有报错即为成功
[root@python ~]# wget https://files.pythonhosted.org/packages/b8/60/f83c7f27d15560c731fb7f39f308b5d056785a0cbb0b5c87ee3767b0db4c/paramiko-1.17.1.tar.gz
[root@python ~]# tar xf paramiko-1.17.1.tar.gz
[root@python ~]# cd paramiko-1.17.1/
[root@python paramiko-1.17.1]# python setup.py build && python setup.py install
测试:
[root@python ~]# python
Python 3.6.0 (default, Nov 6 2018, 18:56:33)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko ###没有报错即为成功
import paramiko
ssh = paramiko.SSHClient()
### 允许连接不在know_hosts主机,不用回答"yes"
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
### 连接本机,端口22,用户root,密码1
ssh.connect('localhost',22,'root','1')
### 执行Linux命令df,结果返回到stdout
stdin,stdout,stderr = ssh.exec_command('df')
res = stdout.read()
print(res.decode())
ssh.close()
import paramiko
transport = paramiko.Transport(('10.10.10.111'),22)
transport.connect(username='root',password='1')
sftp = paramiko.SFTPClient.from_transport(transport)
### 把/etc/passwd放到/tmp下,且命名为passwd(上传)
sftp.put('/etc/passwd','/tmp/passwd')
### 从/etc/passwd下载到当前路径,且命名为passwd_new(下载)
sftp.get('/etc/passwd','passwd_new')
注意:Linux中先要实现免密连接!!!
import paramiko
### 指定路径
private_key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
transport = paramiko.Transport(('10.10.10.111'),22)
### 通过公钥进行链接
transport.connect(username='root',pkey=private_key)
sftp = paramiko.SFTPClient.from_transport(transport)
### 把/etc/passwd放到/tmp下,且命名为passwd.new(上传)
sftp.put('/etc/passwd','/tmp/passwd.new')
### 从/etc/passwd下载到当前路径,且命名为passwd_new(下载)
sftp.get('/etc/passwd','passwd_new')