转载请注明出处,欢迎提出宝贵意见,谢谢!

功能介绍:

1、主机分组
  登录后显示分组主机及主机数量
  选择主机组后显示该主机组下所有主机信息,主机名及IP
显示输入选择:
1、执行命令
利用线程并发组内所有主机同时执行命令,并将结果,返回
格式为:
----------------------host1------------------

----------------------host2------------------

----------------------host3------------------

----------------------host4------------------

2、传输文件

主函数:

#Author by Guangboli
#_*_ coding:utf-8 _*_ import configparser,threading,paramiko,time,os,sys
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
from core import Color_set
color = Color_set.Colorset()
cf = configparser.ConfigParser()
cf.read('config',encoding='utf-8')
secs = cf.sections()
def get_group_info():
'''获取主机组信息'''
print("主机组列表:")
for i in secs:
opts = cf.options(i)
quantity = int(len(opts) / 4)
print(i,'[%s]'%quantity)
def get_host_ip_list(group_name,quantity):
'''获取主机ip列表信息'''
i = 1
while i <= quantity:
print(cf.get(group_name,'ip%s'%i))
i+=1
def cmd_run(ip,username,password,cmd): ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(hostname=ip, port=22, username=username, password=password)
stdin, stdout, stderr = ssh.exec_command(cmd) # 执行命令,不可执行类似vim,top watch命令
result = stdout.read().decode() # 获取结果
tips = color.red('- - - - - %s - - - - - - '.center(20) % ip)
print(tips)
print(result,stderr.read().decode())
except Exception as e:
print('%s 主机发生异常:'%ip,e)
ssh.close()
def transport_put_file(ip,username,password,cmd):
try:
transport = paramiko.Transport((ip, 22))
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(local_file,remote_dir+'/'+put_filename)
except Exception as e:
print(print('%s 主机发生异常:'%ip,e))
transport.close()
def transport_get_file(ip,username,password,cmd):
transport = paramiko.Transport((ip, 22))
try:
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.get(remote_file,local_dir+'\\'+ip+'-'+get_filename) #Linux 需要将\\改为/
except Exception as e:
print(print('%s 主机发生异常:'%ip,e))
transport.close()
def make_treading(func,quantity,group_name,cmd):
i = 1
while i <= quantity:
ip = cf.get(group_name, 'ip%s' % i)
username = cf.get(group_name, 'username%s' % i)
password = cf.get(group_name, 'password%s' % i)
thread = threading.Thread(target=func,args=(ip,username,password,cmd))
thread.setDaemon(True)
thread.start()
i+=1
def welcome():
'''show group and host ip information '''
get_group_info()
global opts,quantity,group_name
while True:
group_name = input('请输入组名(退出请按q or Q):').strip().upper()
if group_name == 'Q':
print('欢迎再次使用,谢谢....')
exit()
elif group_name not in secs:
print("Wrong input,please confirm!")
else:
break
print(group_name,'组下的主机:')
opts = cf.options(group_name)
quantity = int(len(opts) / 4) #hosts quantity
get_host_ip_list(group_name,quantity)
def menu_line2():
global local_dir,local_file,remote_file,remote_dir,get_filename,put_filename
print('''usage:
上传文件:put 本地文件 远程目录
下载文件:get 远程文件 本地目录
退出输入q or Q
examples:
put test.txt /tmp
get /tmp/test.txt /data
''')
while True:
cmd = input("请输入操作:").strip()
args = cmd.split()
if cmd == 'q' or cmd == 'Q':
menu_line1() elif len(args) != 3:
print("输入有误,请重新输入!")
menu_line2()
else:
if args[0] == 'put':
local_file = args[1]
put_filename=args[1].split('/')[-1]
remote_dir = args[2]
func = transport_put_file
make_treading(func, quantity, group_name, cmd)
while threading.active_count() != 1:
time.sleep(0.1)
else:
continue
elif args[0] == 'get':
remote_file = args[1]
get_filename = args[1].split('/')[-1]
local_dir = args[2]
func = transport_get_file
make_treading(func, quantity, group_name, cmd)
while threading.active_count() != 1:
time.sleep(0.1)
else:
continue
else:
print("输入格式有误,请重新输入!")
menu_line2()
def menu_line1():
'''commadns menu'''
func = cmd_run
while True:
print('1、执行命令\n2、传输文件\n')
choice = input("请选择操作:").strip()
if choice == '':
cmd = input("请输入命令:").strip()
print('%s 命令执行结果如下:' % cmd)
make_treading(func,quantity,group_name,cmd)
while threading.active_count() != 1:
# print(threading.active_count())
time.sleep(0.1)
else:
continue
elif choice == '':
menu_line2()
elif choice == 'q' or choice == 'Q':
welcome()
else:
continue
def run():
'''
main function
'''
print('welcome.....')
welcome()
menu_line1() if __name__ == '__main__':
run()

config文件:

[GROUP1]
host1 = host1
ip1 = 10.1.2.3
username1 = root
password1 = 123456
host2 = host2
ip2 = 10.1.2.2
username2 = user1
password2 = 123456
host3 = host3
ip3 = 10.1.2.7
username3 = user2
password3 = 123456 [GROUP2]
host1 = host1
ip1 = 10.1.2.1
username1 = root
password1 = 123456
host2 = host2
ip2 = 10.1.2.2
username2 = root
password2 = 123456
host3 = host3
ip3 = 10.1.2.3
username3 = root
password3 = 123456 [GROUP3]
host1 = host1
ip1 = 10.1.2.1
username1 = root
password1 = 123456
host2 = host2
ip2 = 10.1.2.2
username2 = root
password2 = 123456
host3 = host3
ip3 = 10.1.2.3
username3 = root
password3 = 123456
host4 = host4
ip4 = 10.1.2.4
username4 = root
password4 = 123456
host5 = host5
ip5 = 10.1.2.5
username5 = root
password5 = 123456 [GROUP4]
host1 = host1
ip1 = 10.1.2.1
username1 = root
password1 = 123456
host2 = host2
ip2 = 10.1.2.2
username2 = root
password2 = 123456
host3 = host3
ip3 = 10.1.2.3
username3 = root
password3 = 123456
host4 = host4
ip4 = 10.1.2.4
username4 = root
password4 = 123456
host5 = host5
ip5 = 10.1.2.5
username5 = root
password5 = 123456
host6 = host6
ip6 = 10.1.2.6
username6 = root
password6 = 123456
host7 = host7
ip7 = 10.1.2.7
username7 = root
password7 = 123456

目录结果:

python3 实现堡垒机功能(并发执行命令及上传下载文件)的更多相关文章

  1. 批量执行(Linux命令,上传/下载文件)

    前言: 每个公司的网络环境大都划分 办公网络.线上网络,之所以划分的主要原因是为了保证线上操作安全: 对于外部用户而言也只能访问线上网络的特定开放端口,那么是什么控制了用户访问线上网络的呢? 防火墙过 ...

  2. 【liunx命令】上传下载文件的方法

    scp   帮助命令: man scp   scp功能: 下载远程文件或者目录到本地, 如果想上传或者想下载目录,最好的办法是采用tar压缩一下,是最明智的选择.   从远程主机 下载东西到 本地电脑 ...

  3. centos/redhat命令行上传下载文件

    前言:客户端上没有安装xftp,winscp等等软件,无法将服务器上需要的文件下载到本地去解析,无法将本地的安装包上传到服务器上去,这个时候命令行就可以带你翱翔一波 配置如下: 服务器上: 1.安装需 ...

  4. 【Python】模块学习之使用paramiko连接Linux,远程执行命令,上传下载、文件

    本文主要介绍paramiko远程执行linux命令,及在服务器上进行文件的上传.下载 paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接. ...

  5. SSH命令行上传/下载文件

    上传:scp /path/file(这部分为本地的路径) user(远端目标用户名)@host(远端目标IP):/pathorfile(文件存储路径) 下载:scp user(远端用户名)@host( ...

  6. ARTS-S mac终端ftp命令行上传下载文件

    上传 ftp -u ftp://root:123456@10.11.12.3/a.txt a.txt 下载 ftp -o a.txt ftp://root:123456@10.11.12.13/a.t ...

  7. Linux 使用命令行上传下载文件

    基本语法: 服务器: 用户名@ip:/路径 scp 要拷贝的文件 要存放的文件 上传文件到服务器 # 把本地 source.md 文件上传到 152.116.113.13 服务器的/home目录 # ...

  8. python批量操作Linux服务器脚本,ssh密码登录(执行命令、上传、下载)(一)

     -*-          paramiko.util.log_to_file(         ssh = paramiko.SSHClient()          ssh.set_missing ...

  9. python批量操作Linux服务器脚本,key登录(执行命令、上传、下载)(二)

       -*-   2 #批量操作linux服务器(执行命令,上传,下载)   3 #!/usr/bin/python   4 import paramiko   5 import datetime   ...

随机推荐

  1. jquery自带的排序方法(js也是)

    jquery.sort()   js.sort() <!DOCTYPE html> <html>   <head>     <meta charset=&qu ...

  2. Linux下安装gnuplot

    sudo apt-get install gnuplot 但是在 terminal 里面输入: gnuplot 提示 Terminal type set to unknown.解决方法是安装 x11: ...

  3. boost multi array

    Boost MultiArray is a library that simplifies using arrays with multiple dimensions. 1. #include < ...

  4. pgrep,pidof工具的使用

    博客pgrep,pidof工具的使用 最灵活:ps 选项 | 其它命令 按预定义的模式:pgreppgrep [options] pattern-u uid: effective user,生效者-U ...

  5. linux网络接口,struct ifreq struct ifconf结构

    网络相关的ioctl请求的request参数及arg地址必须指向的数据类型如下表所示: 接口 SIOCGIFCONF SIOCSIFADDR SIOCGIFADDR SIOCSIFBRDADDR SI ...

  6. CSU 1503: 点到圆弧的距离(计算几何)

    题目描述 输入一个点 P 和一条圆弧(圆周的一部分),你的任务是计算 P 到圆弧的最短距离.换句话 说,你需要在圆弧上找一个点,到 P点的距离最小. 提示:请尽量使用精确算法.相比之下,近似算法更难通 ...

  7. react教程 — 组件

    一.state使用: 1.什么时候不能 设置state(或没有必要设置): a.constructor. 2.默认的 state 值,一定要在初始化设置.因为,render 比 setState 早. ...

  8. redis哨兵-5

    #地址: https://www.cnblogs.com/PatrickLiu/p/8444546.html #常用架构 redis1主1从+3哨兵 实现redis高可用 #redis主从 ##### ...

  9. (转)使用InfluxDB+cAdvisor+Grafana配置Docker监控

    文档来源 文档来源:How to setup Docker Monitoring 由garyond翻译.校正及整理 Docker监控简介 我们提供的Docker主机和容器越来越多,对Docker服务器 ...

  10. (转)springboot应用启动原理(一) 将启动脚本嵌入jar

    转:https://segmentfault.com/a/1190000013489340 Spring Boot Takes an opinionated view of building prod ...