单台登录:
#! /bin/bash
# -*- coding: utf-8 -*-
import paramiko
ssh = paramiko.SSHClient()
key = paramiko.AutoAddPolicy()
ssh.set_missing_host_key_policy(key)
pkey = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
ssh.connect('103.11.30.2', 22, 'root', pkey ,timeout=5)
stdin, stdout, stderr = ssh.exec_command('ls')
print(stdout.read().decode())
print(stderr.read())
# 关闭连接
ssh.close()
逐行读取多个IP多台登陆,如下
#!/usr/bin/python
# -*- coding: utf-8 -*-
import time,shutil,os
import paramiko
appname = "root"
ssh = paramiko.SSHClient()
key = paramiko.AutoAddPolicy()
ssh.set_missing_host_key_policy(key)
pkey = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
uptime = time.strftime("%Y%m%d")
warpath="/var/tmp/cslc/aw/update/"+uptime
def update_all_aw():
for line in open("awip.conf"):
print line
ssh.connect(line, 22, appname, pkey ,timeout=5)
stdin, stdout, stderr = ssh.exec_command('python /var/tmp/awpy/createcopy.py')
print(stdout.read().decode())
print(stderr.read())
ssh.close()
print("+++++++下一个++++++")
return
awip.conf文件防止多台IP地址即可。
参考:
python密钥登录主机
pythonparamiko通过密钥文件登陆ssh和听过sftp上传文件
Python使用paramiko库远程安全连接SSH