paramiko支持pip、easy_install或源码方式安装,很好解决包依赖问题具体安装如下:
pip install paramiko
easy_install paramiko
SSH
基于密码:
import paramiko
#基于密码方式
while True:
ssh=paramiko.SSHClient()#创建连接对象
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)#允许连接不在konw_hosts文件中的主机
ssh.connect(hostname="192.168.1.102",port=22,username='root',password=str(123456))#连接服务器
msg=input(">>>:")
stdin,stdout,stderr=ssh.exec_command(msg)#输入,输出,输出错误,执行命令
result=stdout.read()#获取命令结果
print(result.decode())
ssh.close()#关闭连接
基于秘钥:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import paramiko
while True:
private_key=paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect(hostname="192.168.1.102",port=22,username="root",pkey=private_key)
msg=raw_input(">>>")
stdin,stdout,stderr=ssh.exec_command(msg)
result=stdout.read()
print(result)
ssh.close()
FTP
基于密码
import paramiko
transport = paramiko.Transport(('hostname',22))
transport.connect(username='wupeiqi',password='123')
sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')
transport.close()
基于秘钥
import paramiko
private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')
transport = paramiko.Transport(('hostname', 22))
transport.connect(username='wupeiqi', pkey=private_key )
sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')
transport.close()