資安

python 與linux交互 paramiko 自動化運維 批量登錄控制多臺主機執行命令


#!/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

Leave a Reply

Your email address will not be published. Required fields are marked *