#!/usr/bin/python3
import paramiko
client = paramiko.SSHClient() #建立連接配接對象
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
#設定自動添加主機名及主機密鑰到本地HostKeys對 象,不依賴load_system_host_key的配置。跳過yes 連接配接确認提示
try:
client.connect(hostname='eisc.cn',port=22,username='root',password='eisc.cn') #connetc為連接配接 函數
print('主機連接配接成功!')
except:
print('主機連接配接失敗,請确認輸入資訊!')
stdin,stdout,stderr = client.exec_command(
'''
ip a; echo "我是來自python控制系統的程序在操批量操作其它主機;檢視ip資訊: "
echo "需要內建檔案修改闆塊函數"
ls -al ; pwd
'''
) #stdout為指令正确資訊,stderr為指令異常資訊
print(stdout.read().decode('utf-8'))
print(stderr.read().decode('utf-8'))
#####################################################
#!/usr/bin/python3
import paramiko
def SSHLinux(ip,port,username,password,num): # 程式SSH連接配接函數,也是本程式核心方法
a=[] # 定義變量a 為一個清單變量
b=[]
c=[]
d=[]
for i in range(num): # 變量 i 是次數, range() [reɪndʒ] 範圍 函數;可建立一個整數清單;如 range(5) 等于 range(0,5) 生成0到5的自然數
a.append('client' + str(i)) # append [əˈpɛnd] 附加 , 在清單裡附加元素; str() 函數将對象轉化字元串。等同于循環儲存字元串到清單變量a;
b.append('stdin' + str(i))
c.append('stdout' + str(i))
d.append('stderr' + str(i))
a[i] = paramiko.SSHClient() # 建立num個連接配接對象
# client2 = paramiko.SSHClient()
a[i].set_missing_host_key_policy(paramiko.AutoAddPolicy)
# 添加num個主機名及主機密鑰到本地HostKeys對象
# client2.set_missing_host_key_policy(paramiko.AutoAddPolicy)
try:
a[i].connect(hostname=ip[i],port=port[i],username=username[i],password=password[i]) #num個連接配接
# client2.connect(hostname=ip[1],port=port[1],username=username[1],password=password[1])
print(f'主機{ip[i]}連接配接成功!')
except:
print(f'主機{ip[i]}連接配接失敗,請确認輸入資訊!')
exit()
while True: # while True 條件為真 一直進行loop(死循環)
# while true 循環中會加入break條件判斷用以在循環内部的某個條件達成時終止循環
e = (
'''
ls
echo "兩條指令,"
'''
)
for i in range(num):
b[i],c[i],d[i] = a[i].exec_command(e) #num個對象執行e指令
# b[1],c[1],d[1] = a[1].exec_command(e)
# stdin1,stdout1,stderr1 = client2.exec_command(e)
print(f'----------------------{ip[i]}資訊----------------------')
print(c[i].read().decode('utf-8')) # 列印正确輸出
print(d[i].read().decode('utf-8')) # 列印錯誤輸出
# print(f'----------------------{ip[1]}資訊----------------------')
# print(c[1].read().decode('utf-8'))
# print(c[1].read().decode('utf-8'))
if (i < num): # 要求循環次數 小于ip個數
a[i].close()
# a[1].close()
print('已退出SSH連接配接')
break # while true 的條件終止循環語句
def main(): #主方法(運作函數),可以把批量ip端口賬号密碼對應的寫入清單,然後把輸入删掉運作
ip=['hc3.ssh.gs','hc4.ssh.gs']
port=[22,22]
username=['root','root']
password = ['eisc','eisc']
num = len(ip)
SSHLinux(ip,port,username,password,num)
if __name__ == '__main__': # 程式運作入口
main()
# 首先需要配置 python的 pip 的源 參考 linux centos7 編譯安裝python3 --shell腳本
位址1:https://www.eisc.cn/index.php?c=read&id=366&page=1
位址2:https://developer.aliyun.com/article/775858?spm=a2c6h.13148508.0.0.5ea04f0ek5uhm7