[
Python
]一个用
ssh
来远程
登录
多台机器并执行命令的脚本
....
阅读器无法显示某些pdf文档的中文问题 · Ubuntu以及MacOS下使用街机
模拟
器Mame · [
Python
]
Python
3.0来了
...
apc999.blogspot.com/2009/01/python
_19.html -
网页快照
- 类似结果
来源:apc999.blogspot.com/2009/01/python
_19.html(以上为GOOGLE搜索结果,因blogspot被墙了,故转载止此处,供己收藏,亦与众分享)
功能类似于multissh。事实上我也抄了这个名字//grin。
要求安装了
pexpect
这个包先。
用法见usage:
Usage: ./multissh.py -f cmdfile -l username -c cmd -n nodesfile -v -r
execut cmd on remote hosts (all hosts in ./hosts.txt by default)
-v verbose
-r recording hosts on which mission succeeded and failed
-l username
-c cmd to be executed remotely
-n file containing the nodes
-f file conaining the cmd
-h show the usage
就是指定一个文件比如nodes.txt以及命令以后,它可以自动
登录
到nodes.txt包含的节点里执行命令。可以在源文件里替换进你自己的密码,也可以使用公钥密钥
登录
不需输入密码。指定了v选项的话得到在远端每台主机上的详细输出。指定了r选项的话记录下那些节点成功那些节点失败。
我前面的帖子里有关于ansi_color的一个脚本,拿过来可以配合使用得到彩色输出
1. #!/usr/bin/python
2. import sys
3. import os
4. import getopt
5. import pexpect
6. try:
7. from ansi_color import * #就是我前面帖子里关于ansi_color的几个定义
8. except ImportError:
9. def color_str(s, *args):
10. return s
11. fg_green = None
12. fg_red = None
13. fg_blue = None
14. password="123456" #替换成你自己的密码。
15. def do(cmds, dst, username, outfile):
16. global verbose, is_quiet, good_hosts
17. print "executing \"%s\""%(repr(cmds))
18. try:
19. prompt = "^.*\(.*\):|\$"
20. hostname = dst
21. sshcmd = '<b style="color: black; background-color: rgb(153, 255, 153);">ssh</b> %s'%(hostname)
22. if username != None:
23. sshcmd = sshcmd + " -l %s"%username
24. s = pexpect.spawn(command=sshcmd, timeout=20)
25. s.logfile_read = outfile
26. s.setecho(True)
27. i = -1
28. while (i<>0):
29. i = s.expect([prompt,"Are you sure you want to continue connecting (yes/no)?","Password:"])
30. if i == 1:
31. s.sendline("yes")
32. elif i == 2:
33. s.sendline(password)
34. for cmd in cmds:
35. s.sendline(cmd)
36. s.expect(prompt)
37. s.sendline("exit")
38. s.close()
39. if verbose:
40. print
41. print "["+color_str("OK!", fg_green)+"]"
42. if recording:
43. print>>f_good, hostname
44. f_good.flush()
45. good_hosts.append(hostname)
46. except pexpect.ExceptionPexpect:
47. if verbose:
48. print
49. print "["+color_str("Fail!", fg_red)+"]"
50. if recording:
51. print>>f_bad, hostname
52. f_bad.flush()
53. bad_hosts.append(hostname)
54. def print_usage():
55. print "Usage:\t ./make_do.py -f cmdfile -l username -c cmd -n nodesfile -v -r"
56. print "execut cmd on remote hosts (all hosts in ./hosts.txt by default)"
57. print "\t-v verbose"
58. print "\t-r recording hosts on which mission succeeded and failed"
59. print "\t-l username"
60. print "\t-c cmd to be executed remotely"
61. print "\t-n file containing the nodes"
62. print "\t-f file conaining the cmd"
63. print "\t-h show the usage"
64. sys.exit(-1)
65. if __name__ == "__main__":
66. try:
67. opts, args=getopt.getopt(sys.argv[1:], "l:f:n:c:vhr",["login_name", "cmdfile","nodesfile","command","help","verbose", "recording"])
68. except getopt.GetoptError, err:
69. print str(err)
70. print_usage()
71. if opts == [] and args == []:
72. print_usage()
73. hosts = None
74. cmds = None
75. outfile = open("/dev/null", "w")
76. verbose = False
77. username = None
78. recording = False
79. for o, ra in opts:
80. a = ra.strip(" \t\n")
81. if o in ("-h", "--help"):
82. print_usage()
83. elif o in ("-n", "--nodesfile"):
84. h = open(a, 'r')
85. hosts = [l.strip(" \t\n") for l in h]
86. elif o in ("-c", "--command"):
87. cmds = [a]
88. elif o in ("-f", "--cmdfile"):
89. cmdfile = open(a, "r")
90. cmds = [cmd.strip(' \n') for cmd in cmdfile]
91. elif o in ("-v", "--verbose"):
92. outfile = sys.stdout
93. verbose = True
94. elif o in ("-r", "--recording"):
95. recording = True
96. elif o in ("-l", "--login_name"):
97. username = a
98. if hosts is None:
99. print "using default ./hosts.txt"
100. h = open(os.path.join(os.path.expanduser("."), "hosts.txt"),'r')
101. hosts = [dst.strip(' \n') for dst in h]
102. if cmds is None:
103. print "-c or -f must specified"
104. print_usage()
105. if recording:
106. f_good = open("good_hosts.txt","w")
107. f_bad = open("bad_hosts.txt","w")
108. good_hosts =[]
109. bad_hosts =[]
110. for i in range(len(hosts)):
111. dst = hosts[i]
112. print "%d/%d: ["%(i+1, len(hosts))+ color_str(dst, fg_blue)+"]"
113. do(cmds, dst, username, outfile)
114. print "%d hosts suceed!"%len(good_hosts)
115. outfile.close()
116. h.close()
另附一个邮件列表组的讨论内容:
python-cn邮件列表 写道
python
能不能模拟键盘输入字符,类似于TCL的post,比如在我用SSH
连接到LINUX,然后用PYTHON
来输入ls命令。急用
pyexpect
2008/11/25 zhezh80 <zhezh80@...>:
> python能不能模拟键盘输入字符,类似于TCL的post,比如在我用SSH连接到LINUX,然后用PYTHON来输入ls命令。急用
>
你这个并非模拟键盘输入,
而仅仅是远程通过 ssh 执行命令,
请阅以前讨论过的 python-paramiko
分享到:
相关推荐
Python – paramiko 模块远程执行ssh 命令 nohup 不生效的问题解决 1、使用 paramiko 模块ssh 登陆到 linux 执行nohup命令不生效 # 执行命令 def command(ssh_config, cmd, result_print=None, nohup=False): ssh ...
注: 该脚本需要调用的模块为:paramiko, sys, ... 批量执行命令格式: -C "IP列表" -M '执行的命令' 批量传送文件: -S "IP列表" -L "本地文件路径" -R "远程文件路径" 错误日志文件:$PWD/ssh_errors.log
用python SSH模块登录,并在远程机执行shell命令 (在CentOS 7 环境试验成功, Redhat 系列应该是兼容的。) 先安装必须的模块 # yum install python-dev # yum install python-devel # pip install pycrypto # ...
一个用python写的监控脚本test1.py,用while True方式一直运行,在ssh远程(使用putty终端)时通过以下命令启动脚本: 代码如下: python test1.py & 现在脚本正常运行,通过ps能看到进程号,此时直接关闭ssh终端...
跳转SSH JumpSSH: Python模块可在远程服务器上运行命令 ... 那么,为什么还要另一个python库通过ssh设置远程服务器呢? 这是与最知名的现有python库的快速比较 Paramiko:在python中提供了SSHv2协议
下面是一个简单的自动化运维脚本示例,用于管理远程服务器的基本操作,如执行命令、上传文件、下载文件等。这个脚本使用了Python语言和Paramiko库来实现SSH连接和远程操作。使用该脚本前,确保已安装Paramiko库(可...
ssh_thread.py 是一个批量执行命令的脚本,支持直接执行ssh命令及文件传输,支持多线程 使用说明如下: -h,-H,--help 帮助页面 -C, --cmd 执行命令模式 -M, --command 执行命令模式 -S, --sendfile 传输...
1. ssh_thread.py 是一个批量执行命令的脚本,支持直接执行ssh命令及文件传输,支持多线程 使用说明如下: -h,-H,--help 帮助页面 -C, --cmd 执行命令模式 -M, --command 执行命令模式 -S, --sendfile ...
首先我们做一个定时或者实时脚本timedtask.py,让其定时监控目标服务器,两种方式: 第一种: #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/11/27 15:59 # @Desc : 定时任务,以需要的时间间隔...
ssh 这是一个简单的脚本,可用于日常在远程linux / unix风味机器上执行命令/复制文件的示例用法: 导入ssh sshclient = ssh(“ 10.213.157.25”,“ root”,“ Recnex#1”) sshclient.execute(“ mkdir -p / ...
如何运行脚本: 在外壳中,运行“ easy_install paramiko” 转到脚本目录方法1: 使用以下命令运行脚本:“ python mysql-remote-dump.py” 填写表格方法2: 使用以下命令运行脚本:“ python mysql-remote-dump.py...
为了自动化地完成这个任务,我们可以编写一个Python脚本来实现文件的实时同步功能。本篇博客将介绍如何使用Python脚本,结合watchdog和paramiko库,实现文件的实时同步。 该脚本的主要功能是: 监测本地指定目录的...
Python脚本通过连接winRM模块操作windows命令行。 import winrm def cmd_views(ip,cmd_comand): win = winrm.Session('http://'+ip+':5985/wsman', auth=('user', 'password'))#参数为用户名和密码 r = w
linux机器日常运维过程中,经常需要在本地运行脚本执行针对远程主机的命令。正常情况下,ssh登陆远程机器时会提示输入密码,这会影响到脚本的自动执行,(因为shell脚本中没有自动填充密码的命令)。 总的来说,...
※用多线程的方式并发连接登录多台LINUX服务器,实现并发命令操作、文件分发,实时结果返回,并可根据服务器性能控制线程量,千台机器改密码1分钟完成。 3、HTML/JAVAScript基础 4、WEB JS Package BootStrap 介绍...
包含python脚本概述、脚本调试和性能测试、单元测试、自动化常规运维、文件目录和数据处理、文件存档、加密和解密、文本处理和正则表达式、文档和报告、操作文件、网络基础Socket编程、python脚本处理邮件、Telnet和...
关于使用paramiko执行远程主机命令可以找到很多参考资料了,本文在此基础上做一些封装,便于扩展与编写脚本。 下面直接给出代码: # coding: utf-8 import paramiko import re from time import sleep # 定义一个类...
没有代码可将您的设置从旧的JSON格式迁移到INI格式,因此请检查您的设置并删除旧的JSON文件除了设置的新格式外,这些脚本的较新版本现在还支持通过Telnet和SSH初始化到远程设备的连接,以及通过跳转/堡垒主机的连接...