我有python脚本将从文件读取每个IP并使用密码在该IP上安装代理,有5-6个密码,如果一个密码不起作用,它应该逐个尝试其他所有密码。 我的一个密码的脚本代码是:
p = subprocess.Popen(["./linux_autodisc"], stdout=subprocess.PIPE)
p1 = str(p.communicate())
if '1 devices were successfully added/updated' in p1:
print ('Sucessfull Completed Ip: ' +line)
f6 = open("/root/nix_bsd_mac_inventory-master/SucessfullIp.txt","a")
f6.write("\n"+line)
f6.close()
else:
print "Unsuccessfull"
我如何可以包含多个else来运行5-6密码的脚本,而对于最后一个它应该返回尝试所有密码而不成功。
答案 0 :(得分:1)
为了保持代码清洁,我建议提取这样的函数:
def try_password(password):
``code that uses the password``
for password in password_array:
successful = try_password(password)
if successful:
break
堆叠else语句会使您的代码更难以阅读/理解,并且会使未来的更改变得复杂。
这是我对你的脚本的建议:
##Reading values from SucessfullIp.txt
with open('/root/nix_bsd_mac_inventory-master/SucessfullIp.txt') as f:
ips = set(line.rstrip() for line in f)
password_list = ["password1","password2"]
##Reading Unique Ip's values
with open("/root/nix_bsd_mac_inventory-master/Unique.txt") as fp:
for line in fp:
line = line.rstrip()
## Comparing unique ip's if ip is already has scanned
if line in ips:
print('{}: Ip is Already Tried: '.format(line))
else:
##Creating inventory.cfg file on the fly for each ip
for password in password_list:
if try_password(password):
print ('Sucessfull Completed Ip: ' +line)
f6 = open("/root/nix_bsd_mac_inventory-master/SucessfullIp.txt","a")
f6.write("\n"+line)
f6.close()
break
else:
print "Unsuccessfull for {}".format(password) ## dont break and check others
## Extracted function to use password
## This could perhaps be optimized by extracting repetative tasks (depends on usage/performance)
def try_password(password):
f3 = open("/root/nix_bsd_mac_inventory-master/inventory.cfg", "w")
print "Processing Ip: " + line
##here we are giving credentials
write_string = "[device42_access]" + "\n" +
"base_url = https://1.8.0.3" + "\n" +
"username = uname" + "\n" +
"secret = abcd" + "\n" +
"[discover]" + "\n" +
"cpu= true" + "\n" +
"hardware = true" + "\n" +
"memory = true" + "\n" +
"[access]"+ "\n" +
"credentials = username:{}"
f3.write(write_string.format(password))
f3.close()
p = subprocess.Popen(["./d42_linux_autodisc_v620"], stdout=subprocess.PIPE) ##This script will require inventory.cfg file created above
p1 = str(p.communicate())
return '1 devices were successfully added/updated' in p1