我是一个Python和开发人员的完整新手,我被困在一个项目中。如何使用函数来填充for循环中的变量?
我有一个函数可以从我的Salt Master中获取服务器列表。然后,我尝试在for循环中使用该列表来连接到该服务器并将我的公钥复制到它们。当我硬编码服务器运行没有问题。它看起来像我的for循环中的变量不返回任何东西。
这是我的For循环。
def deploy_key(key, server, username, password):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(server, username=username, password=password)
transport = ssh.get_transport()
session = transport.open_session()
session.set_combine_stderr(True)
session.get_pty()
session = transport.open_session()
session.set_combine_stderr(True)
session.get_pty()
for commands in l_commands:
session = transport.open_session()
session.set_combine_stderr(True)
session.get_pty()
session.exec_command(commands)
stdin = session.makefile('wb', -1)
stdout = session.makefile('rb', -1)
stdin.write(password + '\n')
stdin.flush()
username = "myUserName"
password = "myPassword"
server = hosts()
user = getUser()
key = getKey()
l_commands = ['sudo mkdir -p /home/%s/.ssh/' % user,'sudo chmod -R 777 /home/%s' %user,
'sudo echo "%s" >> /home/%s/.ssh/authorized_keys' %(key, user),
'sudo chmod 644 /home/%s/.ssh/authorized_keys' % user,
'sudo chmod 700 /home/%s/.ssh/' % user, 'sudo chmod 755 /home/%s' %user]
for host in server:
deploy_key(key, host, username, password)
这里是我的函数来获取变量
import paramiko
l_password = "myPassword"
l_host = "saltMaster.salt.com"
l_commands = "sudo salt-key -L"
l_user = "myUser"
def hosts():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(l_host, username=l_user, password=l_password)
transport = ssh.get_transport()
session = transport.open_session()
session.set_combine_stderr(True)
session.get_pty()
session = transport.open_session()
session.set_combine_stderr(True)
session.get_pty()
session.exec_command(l_commands)
stdin = session.makefile('wb', -1)
stdout = session.makefile('rb', -1)
stdin.write(l_password + '\n')
stdin.flush()
for line in stdout.read().splitlines():
input_line = line
input_line = input_line.replace(b"\x1b[0;32m", b'') # remove \x1b[1;32m
input_line = input_line.replace(b"\x1b[0;0m", b'') # remove \x1b[1;35m
input_line = input_line.replace(b"\x1b[0;1;34mRejected Keys:", b'') # remove \x1b[1;36m
input_line = input_line.replace(b"\x1b[0;1;31mUnaccepted Keys:", b'') # remove \x1b[1m
input_line = input_line.replace(b"\x1b[0;1;35mDenied Keys:", b'') # remove \x07 (BEL)
input_line = input_line.replace(b"\x1b[0;1;32mAccepted Keys:", b'') # remove \x07 (BEL)
input_line = input_line.replace(b"Freedom1", b'') # remove \x07 (BEL)
hostsIndividual = str(input_line,"utf-8")
return(hostsIndividual)
在你的for循环之前'l_commands'持有什么,你能打印出来以确保它是你想要的吗?同样对于你的'host'函数,为什么你要在第一次for循环迭代之后返回?如果只是一个迭代,为什么首先需要for循环呢? – MooingRawr
'hosts()'函数只会返回一个'hostsIndividual'值,因为你有一个'return'语句在其中的'for'循环。 – martineau