paramiko模擬ansible遠端執行命令

2022-05-27 08:09:12 字數 2953 閱讀 1884

主模組

#!/usr/bin/env python

from multiprocessing import process

import paramiko

import time

import sys

import new_latest_configparser #匯入配置資訊模組

# import groupshow

username = "root"

password = "123456"

port = 22

current_time = time.strftime("%y-%m-%d %x", time.localtime())

#執行命令處

def runcmd(ip,cmd):

s = paramiko.sshclient()

s.set_missing_host_key_policy(paramiko.autoaddpolicy())

try:

s.connect(hostname=ip,port=port,username=username,password=password)

stdin,stdout,stderr = s.exec_command(cmd)

result = stdout.read()

# print(result)

s.close()

print("ip:[%s]at:[%s] run command [%s]".center(50, "-") % (ip, current_time,cmd))

print(str(result, encoding="utf-8"))

except:

print("%s is not exits" %ip)

# if_continue = input("請輸入是否需要繼續輸入命令,是按[y],否按[n]")

def handle_process():

while true:

print("歡迎來到ansible模擬系統,主機分組如下".center(50, "-"))

#呼叫主機資訊模組方法

new_latest_configparser.showgroups()

user_choice = str(input("請選擇組:").strip())

if len(user_choice) == 0 or user_choice not in new_latest_configparser.group or user_choice.isdigit():

print("請輸入正確的組名")

continue

elif user_choice == "webserver":

#列印主機資訊處

print(new_latest_configparser.config.get("webserver", "ip"))

print(new_latest_configparser.config.get("webserver", "ip2"))

break

elif user_choice == "dbserver":

# print(functions.config.get("dbserver"))

print(new_latest_configparser.config.get("dbserver","ip"))

break

try:

cmd = input("please input your cmd:")

#判斷主機組

if user_choice == "webserver":

#迴圈獲取ip

for ip in new_latest_configparser.iplist:

p = process(target=runcmd,args=(ip,cmd))

p.start()

elif user_choice == "dbserver":

for ip in new_latest_configparser.other_list:

p = process(target=runcmd, args=(ip, cmd))

p.start()

except indexerror:

print("please input a command")

if __name__ == '__main__':

handle_process()

配置資訊模組

import configparser

config = configparser.configparser()

config.read("host.conf")

sec = config.sections()

kvs = config.items("webserver")

group = [

"webserver",

"dbserver"

]ip = str(kvs[0][1])

ip2 = str(kvs[1][1])

iplist =

#另外一組資訊

other_kvs = config.items("dbserver")

new_ip = str(other_kvs[0][1])

other_list =

def showgroups():

for group in sec:

print(group)

配置資訊

[webserver]

ip = 192.168.170.143

ip2 = 192.168.170.150

[dbserver]

ip = 192.168.170.129

執行結果

ansib通過跳板機管理機器

jump hosts 一 通過一台跳板機免密 a主機 b跳板機 c主機 做好a免密登入b,b免密登入c a主機 ssh下新增檔案b private,內容為b的私鑰 a主機 ssh下增加config檔案,內容為 host c主機ip user gcp port 22 identityfile ssh ...

paramiko 遠端登入

from paramiko import hostname ip port 22 username root password x util.log to file paramiko.log s sshclient s.load system host keys s.connect hostname...

paramiko 模組安裝

windows版本 需要的軟體包 pycrypto ecdsa paramiko 1 pycrypto的安裝自己下一步機可以了。2 安裝ecdsa,直接用cmd進入ecdsa目錄下,輸入 python setup.py install 3 安裝paramiko,和ecdsa一樣,進入paramiko...