paramiko模块提供了ssh及sft进行远程登录服务器执行命令和上传下载文件的功能。这是一个第三方的软件包,使用之前需要安装
paramiko远程密码连接
import paramiko
#创建一个ssh对象
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
#连接服务器
client.connect(
hostname='172.25.254.36',
username='root',
password='redhat'
)
#执行操作
stdin, stdout, stderr = client.exec_command('hostname')
#获取命令的执行结果
print(stdout.read().decode('utf-8'))
#关闭连接
client.close()
批量远程密码连接
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException
def connect(cmd, hostname, user, password):
import paramiko
# ssh [email protected]
# 创建一个ssh对象;
client = paramiko.SSHClient()
# 2. 解决问题:如果之前没有;连接过的ip, 会出现
# Are you sure you want to continue connecting (yes/no)? yes
# 自动选择yes
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 3. 连接服务器
client.connect(
hostname=hostname,
username=user,
password=password
)
except NoValidConnectionsError as e:
return "主机%s连接失败" %(hostname)
except AuthenticationException as e:
return "主机%s密码错误" % (hostname)
except Exception as e:
return "未知错误: ", e
else:
# 4. 执行操作
stdin, stdout, stderr = client.exec_command('hostname')
# 5. 获取命令的执行结果;
res = stdout.read().decode('utf-8')
# 6. 关闭连接
client.close()
return res
if __name__ == '__main__':
with open('doc/hosts.txt') as f:
for line in f:
# 172.25.254.1:root:westos
hostname, username, password = line.split(":")
res = connect('hostname', hostname, username, password )
print(hostname.center(50, '*'))
print("主机名:", res)
在文本中随便写入一些用户进行测试
paramiko基于公钥和私钥连接
目标:
1). 172.25.254.3 - host3
172.25.254.4 - host4
2). host4实现无密码连接host3?
*****host3操作: 生成公钥和私钥, 并发送私钥给host4
993 ssh-keygen
994 cd /root/.ssh/
995 ls
996 ssh-copy-id -i id_rsa.pub [email protected]
997 scp id_rsa [email protected]:/home/kiosk/.ssh/
*****host4操作:
a). shell命令检测是否可以成功?
ssh [email protected]
b). 代码实现:
import paramiko
# ssh [email protected]
# 创建一个ssh对象;
client = paramiko.SSHClient()
# 实例化一个私钥对象
private_key = paramiko.RSAKey.from_private_key_file('/home/kiosk/.ssh/id_rsa')
# 2. 解决问题:如果之前没有;连接过的ip, 会出现
# Are you sure you want to continue connecting (yes/no)? yes
# 自动选择yes
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 3. 连接服务器
client.connect(
hostname='172.25.254.36',
username='root',
pkey= private_key ,
)
# 4. 执行操作
stdin, stdout, stderr = client.exec_command('hostname')
# 5. 获取命令的执行结果;
print(stdout.read().decode('utf-8'))
# 6. 关闭连接
client.close()