首页 \ 问答 \ 简述foreach循环的语法结构和功能

简述foreach循环的语法结构和功能

简述foreach循环的语法结构和功能
更新时间:2021-06-13 08:06

最满意答案

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
import pexpect 
def ssh_cmd(ip, passwd, cmd): 
ret = -1 
ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd)) 
try: 
i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5) 
if i == 0 : 
ssh.sendline(passwd) 
elif i == 1: 
ssh.sendline('yes\n') 
ssh.expect('password: ') 
ssh.sendline(passwd) 
ssh.sendline(cmd) 
r = ssh.read() 
print r 
ret = 0 
except pexpect.EOF: 
print "EOF" 
ssh.close() 
ret = -1 
except pexpect.TIMEOUT: 
print "TIMEOUT" 
ssh.close() 
ret = -2 
return ret 

利用pexpect模块我们可以做很多事情,由于他提供了自动交互功能,因此我们可以实现ftp,telnet,ssh,scp等的自动登录,还是比较实用的。根据上面的代码相信读者已经知道怎么实现了(python就是那么简单!)。 
用
上面的代码去完成任务还是比较费时间的,因为程序要等待自动交互出现,另外ubuntu用ssh连接就是比较慢,要进行一系列的验证,这样才体现出ssh
的安全。我们要提高效率,在最短的时间内完成。后来我发现了python里面的paramiko模块,用这个实现ssh登录更加简单。看下面的代码: 

复制代码 代码如下:

#-*- coding: utf-8 -*- 
#!/usr/bin/python 
import paramiko 
import threading 
def ssh2(ip,username,passwd,cmd): 
try: 
ssh = paramiko.SSHClient() 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh.connect(ip,22,username,passwd,timeout=5) 
for m in cmd: 
stdin, stdout, stderr = ssh.exec_command(m) 
# stdin.write("Y") #简单交互,输入 ‘Y' 
out = stdout.readlines() 
#屏幕输出 
for o in out: 
print o, 
print '%s\tOK\n'%(ip) 
ssh.close() 
except : 
print '%s\tError\n'%(ip) 
if __name__=='__main__': 
cmd = ['cal','echo hello!']#你要执行的命令列表 
username = "" #用户名 
passwd = "" #密码 
threads = [] #多线程 
print "Begin......" 
for i in range(1,254): 
ip = '192.168.1.'+str(i) 
a=threading.Thread(target=ssh2,args=(ip,username,passwd,cmd)) 
a.start() 

上面的程序还是有些技巧的: 
1.
利用多线程,同时发出登录请求,同时去连接电脑,这样速度快很多,我试了一下,如果不用多线程,直接一个一个挨着执行的话,大约5~10秒钟才能对一台电
脑操作完,具体时间要根据命令的来决定,如果是软件安装或者卸载时间要更长一些。这样下来怎么也要一二十分钟,用多线程后就快多了,所有的命令执行完用了
不到2分钟! 
2.最好用root用户登录,因为安装或者卸载软件的时候如果用普通用户又会提示输入密码,这样又多了一次交互,处理起来就比较麻
烦!安装软件时apt-get install xxx 
最好加上“-y”参数,因为有时安装或删除软件时提示是否继续安装或卸载,这又是一次自动交互!加上那个参数后就没有人机交互了。 
3. 循环时循环所有ip,因为计算机的ip是路由器自动分配的,保险起见,最好全部都执行,保证没有遗漏的主机 
4.远端执行命令时如果有交互,可以这样用 stdin.write("Y")来完成交互,“Y”就是输入“Y”。 
5.把所有的命令放到一个列表里面,遍历列表可以依次执行列表里面的命令 
6.为了更好的进行控制,最好在电脑上提前把root用户打开,装好ssh服务器并让其开机自动执行。

其他回答

任务占坑

相关问答

更多
  • 代码如下: #!/usr/bin/env python# -*- coding: utf-8 -*-# @name : find_t.py# @author : cat# @date : 2017/8/2.import osimport timedef bash_shell(bash_command): """ python 中执行 bash 命令 :param bash_command: :return: bash 命令执行后的控制台输出 """ try: return os.popen(bash_com ...
  • #!/usr/bin/env python # -*- coding: utf-8 -*- import pexpect def ssh_cmd(ip, passwd, cmd): ret = -1 ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd)) try: i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5) if i == 0 : ssh.sendline( ...
  • 安装一个pyyaml库。它会解析这个文件,变成一个类似json加载后的结构。字典,列表什么的。然后自己找参数。 ssh命令同样要使用一个库。简单的办法是通过一个封装popen这样功能 的pexpect , 我以前用过paramiko。 另外似乎还有一个SSH库,最近流行的。不记得名子了。 也有人用ssh4py 这个库。 yaml这个格式比较人性化,易读,易管理。比json还要简单。比xml少了编码和解析成DOM的麻烦。
  • python 问题[2023-06-21]

    这。。。本身得出的pwd是有问题的,你可以试着将pwd打印出来看下。如果你要进入目录,可以试着用os.chdir()
  • 根据文件的大小,你可以做如下的事情: ... files= "file1 file2 ..." myvar = "" for tm in machine_list myvar = myvar+ subprocess.check_output(["ssh", "user@" + tm, "/bin/cat " + files]); ... file1 file2等是空格分隔的。 假设所有的unix盒子都可以在每台机器上一次性完成/ bin / cat。 (这是假设您只是将一个变量的整个内容 ...
  • 我会把你转到paramiko 看到这个问题 ssh = paramiko.SSHClient() ssh.connect(server, username=username, password=password) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute) I will refer you to paramiko see this question ssh = paramiko.SSHClient() ssh.c ...
  • 注意错误消息中“abc.local”和后面冒号之间的换行符:从第一个Popen返回的实际字符串是“abc.local \ n”。 你需要.strip()或以其他方式摆脱那个换行符。 Notice the line break between "abc.local" and the following colon in the error message: the actual string you got back from the first Popen is "abc.local\n". You nee ...
  • 如果你想要简单的方法,这应该是正常的。 您将要首先“.close()”文件,以便您知道它从Python中刷新到磁盘。 import os os.system("scp FILE USER@SERVER:PATH") #e.g. os.system("scp foo.bar joe@srvr.net:/path/to/foo.bar") 您需要事先生成(在源计算机上)并安装(在目标计算机上)ssh密钥,以便scp自动使用公共ssh密钥进行身份验证(换句话说,因此您的脚本不要求密码) 。 ssh-keygen ...
  • 使用paramiko 。 它是ssh和scp最好的python包之一。 链接: python paramiko ssh http://www.paramiko.org/ Use paramiko. it is one of the best python package for ssh and scp. link: python paramiko ssh http://www.paramiko.org/
  • 改用paramiko的SFTP客户端。 此示例程序在复制之前检查是否存在。 #!/usr/bin/env python import paramiko import getpass # make a local test file open('deleteme.txt', 'w').write('you really should delete this]n') ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.Au ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)