欢迎光临
一个有态度、有温度的分享型博客

Python之paramiko模块

paramiko模块是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接。

1.安装

手动安装:

#paramiko模块的安装需要先安装PyCrypto模块
wget  https://pypi.python.org/packages/source/p/pycrypto/pycrypto-2.6.1.tar.gz
wget
cd pycrypto-2.6.1
python setup.py build
python setup.py install
https://pypi.python.org/packages/source/p/paramiko/paramiko-1.13.0.tar.gz
cd paramiko-1.13.0
python setup.py build
python setup.py install

yum安装

yum -y  install python-crypto python-paramiko

测试

>>> import paramiko
>>> dir(paramiko)
['AUTH_FAILED', 'AUTH_PARTIALLY_SUCCESSFUL', 'AUTH_SUCCESSFUL', 'Agent', 'AgentKey', 'AuthHandler', 'AuthenticationException', 'AutoAddPolicy', 'BadAuthenticationType', 'BadHostKeyException', 'BaseSFTP', 'BufferedFile', 'Channel', 'ChannelException', 'ChannelFile', 'DSSKey', 'HostKeys', 'InteractiveQuery', 'Message', 'MissingHostKeyPolicy', 'OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED', 'OPEN_FAILED_CONNECT_FAILED', 'OPEN_FAILED_RESOURCE_SHORTAGE', 'OPEN_FAILED_UNKNOWN_CHANNEL_TYPE', 'OPEN_SUCCEEDED', 'PKey', 'Packetizer', 'PasswordRequiredException', 'RSAKey', 'RejectPolicy', 'SFTP', 'SFTPAttributes', 'SFTPClient', 'SFTPError', 'SFTPFile', 'SFTPHandle', 'SFTPServer', 'SFTPServerInterface', 'SFTP_BAD_MESSAGE', 'SFTP_CONNECTION_LOST', 'SFTP_EOF', 'SFTP_FAILURE', 'SFTP_NO_CONNECTION', 'SFTP_NO_SUCH_FILE', 'SFTP_OK', 'SFTP_OP_UNSUPPORTED', 'SFTP_PERMISSION_DENIED', 'SSHClient', 'SSHConfig', 'SSHException', 'SecurityOptions', 'ServerInterface', 'SubsystemHandler', 'Transport', 'WarningPolicy', '__all__', '__author__', '__builtins__', '__date__', '__doc__', '__file__', '__license__', '__name__', '__package__', '__path__', '__version__', '__version_info__', 'agent', 'auth_handler', 'ber', 'buffered_pipe', 'channel', 'client', 'common', 'compress', 'config', 'dsskey', 'file', 'hostkeys', 'kex_gex', 'kex_group1', 'message', 'packet', 'pipe', 'pkey', 'primes', 'randpool', 'resource', 'rng', 'rng_posix', 'rsakey', 'server', 'sftp', 'sftp_attr', 'sftp_client', 'sftp_file', 'sftp_handle', 'sftp_server', 'sftp_si', 'ssh_exception', 'sys', 'transport', 'util']
>>>

例子1:ssh到多台主机,执行相同的命令。

#!/usr/bin/python
import paramiko
USER = 'root'
PASSWORD = '123456'
COMMAND = 'mkdir 888'
for line in open('/root/ip.txt'):
    IP = line
    paramiko.util.log_to_file('/root/zhu.log')
    s = paramiko.SSHClient()
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    s.connect(hostname=IP,username=USER,password=PASSWORD)
    s.exec_command(COMMAND)
    s.close
###############
[root@zhu ~]# cat ip.txt
192.168.56.101
192.168.56.102

例子2:把指定的文件上传到多台主机上。

#!/usr/bin/python
import paramiko
PORT = 22
USER = 'root'
PASSWORD = '123456'
REMORE_PATH = '/tmp/qianshan.txt'
LOCAL_PATH = '/root/1.txt'
for line in open('/root/ip.txt'):
    IP = line
    t = paramiko.Transport((IP,PORT))
    t.connect(username=USER,password=PASSWORD)
    s = paramiko.SFTPClient.from_transport(t)
    s.put(LOCAL_PATH,REMORE_PATH)
    t.close
###################
192.168.56.101
192.168.56.102

paramiko.SSHClient() :建立一个连接到ssh服务器的实例。

#常见用法如下:
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #允许连接不在know_hosts中的主机,默认是拒绝的。
s.connect(hostname=IP,username=USER,password=PASSWORD) #连接到远程主机
s.exec_command() #在远程主机上执行命令

exec_command(self, command, bufsize=-1, timeout=None, get_pty=False) #作为paramiko.SSHClient()的方法,该方法用于在ssh服务器上执行命令,命令执行的输入,输出流作为python的类文件对象返回,命令执行返回的是一个元组,
所以查看命令的执行输出,常用方法如下:
stdin, stdout, stderr = s.exec_command('ls')
print stdout.readlines()

简单的同时在多台主机上执行相同的指令:

[root@zhu ~]# ./zhu.py 192.168.56.102 192.168.56.101 ' ls -l'
192.168.56.102:
总用量 4
drwxr-xr-x. 2 root root 4096 5月   7 15:36 mypackages
192.168.56.101:
总用量 56
-rwxr-xr-x. 1 root root   432 5月   8 14:42 jiang.py
drwxr-xr-x. 2 root root  4096 5月   5 17:09 mypython
drwxr-xr-x. 2 root root  4096 5月   5 14:28 mysource
drwxr-xr-x. 3 root root  4096 5月   1 16:22 mywork
drwxr-xr-x. 2 root root 36864 5月   5 17:09 pythoncook
-rwxr-xr-x. 1 root root   535 5月   8 15:10 zhu.py
[root@zhu ~]# cat zhu.py
#!/usr/bin/python
import paramiko
import sys
USER = 'root'
PASSWORD = '123456'
COMMAND = sys.argv[-1]
if len(sys.argv[1:]) < 2:
    print 'The arguments must more than two'
else:
    for IP in sys.argv[1:-1]:
        print IP + ':'
        s = paramiko.SSHClient()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())  
        s.connect(hostname=IP,username=USER,password=PASSWORD)
        for i in s.exec_command(COMMAND)[1].readlines():
            print i,
        s.close
#how to use: python zhu.py ip1 ip2 'command'

参考:

  1. http://caisangzi.blog.51cto.com/6387416/1390759;
  2. http://www.cnblogs.com/starof/p/4670433.html;
  3. http://blog.csdn.net/five3/article/details/8099997;
转载请注明出处:容休博客 » Python之paramiko模块

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址