1、安装pyCrypto
安装这个比较麻烦,需要本地编译,要装vs或gcc还有一堆配置,还不一定能编译成功。(网上能搜到安装步骤)
建议直接下载已编译版: http://www.voidspace.org.uk/python/modules.shtml#pycrypto
直接下载并安装既可。
(注:crypto有java和C++版)
2、安装ecdsa
看很多博客没有提到这个库,但我执行paramiko时,提示找不到ecdsa模块。
下载:https://pypi.python.org/pypi/ecdsa/0.9 ,解压到一个目录,目录中有一个setup.py。
安装比较简单,windows下直接在刚才解压后的目录执行:python setup.py install
3.安装paramiko
与安装ecdsa类型,只是打开下载页面很慢。。。
下载: https://github.com/paramiko/paramiko#,
安装步骤同ecdsa
注:1、所有另外安装的第三方库,如果不特指定安装后库目录的话,将默认保存到 %PYTHON_HOME%\Lib\site-packages下。
2、python大小写敏感,对模块名也是。
3、Crypto可以提供常见的加解密算法,如:RSA、RC4、DSA、DES
测试例子:
- # _*_ coding:UTF-8 _*_
- def t5():
- '''''Crypto MD5'''
- from Crypto.Hash import MD5
- h = MD5.new()
- h.update(b'Hello')
- print h.hexdigest()
- def t6():
- import paramiko
- hostname = '192.168.9.57'
- port = 22
- user = 'root'
- passwd = '123456'
- paramiko.util.log_to_file('paramiko.log')
- s = paramiko.SSHClient()
- s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- s.connect(hostname=hostname,port=port,username=user, password=passwd)
- #stdin,stdout,stderr=s.exec_command('pwd')
- stdin,stdout,stderr=s.exec_command('cat /etc/passwd | grep root:x:0:0:root', timeout=5)
- #print stdout.read()
- lines = stdout.readlines()
- for i in lines:
- print splitline(i)
- #print i,
- s.close()
- def splitline(line='', ch=':'):
- tmp = line[0:len(line)-1]
- ss = tmp.split(ch)
- ret = ''
- for i in ss:
- ret += i
- ret += ' '
- #print i + '===',
- return ret
- if __name__ == "__main__":
- #t7()
- t6()
- #t5()
模拟远程文件传输:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import
paramiko
#建立一个加密的管道
scp
=
paramiko.Transport((
'10.1.6.190'
,
22
))
#建立连接
scp.connect(username
=
'root'
,password
=
'password'
)
#建立一个sftp客户端对象,通过ssh transport操作远程文件
sftp
=
paramiko.SFTPClient.from_transport(scp)
#Copy a remote file (remotepath) from the SFTP server to the local host
sftp.get(
'/root/debian7'
,
'/tmp/debian7'
)
#Copy a local file (localpath) to the SFTP server as remotepath
sftp.put(
'/root/crash-6.1.6.tar.gz'
,
'/tmp/crash-6.1.6.tar.gz'
)
scp.close()
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
import
paramiko
import
interactive
#记录日志
paramiko.util.log_to_file(
'/tmp/test'
)
#建立ssh连接
ssh
=paramiko.SSHClient()
ssh
.load_system_host_keys()
ssh
.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh
.connect(
'10.1.6.190'
,port=22,username=
'root'
,password=
'xxxxxx'
,compress=True)
#建立交互式shell连接
channel=
ssh
.invoke_shell()
#建立交互式管道
interactive.interactive_shell(channel)
#关闭连接
channel.close()
ssh
.close()
|
参考文章:
http://blog.chinaunix.net/uid-24917554-id-3476396.html
http://lili-xiang.iteye.com/blog/1796640
api:
https://www.dlitz.net/software/pycrypto/api/current/ https://www.dlitz.net/software/pycrypto/doc/
http://docs.paramiko.org/