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