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
Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡