如何使用函数来填充for循环中的变量?

时间:2016-12-28 18:27:24

标签: python python-3.x

我是Python和开发的完全新手,我坚持一个项目。

我有一个函数可以从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)

2 个答案:

答案 0 :(得分:1)

问题出在hosts()方法的返回语句中。

def hosts():
    // your code goes here

    for line in stdout.read().splitlines():
        // your code goes here
        hostsIndividual = str(input_line,"utf-8")
        return(hostsIndividual)

这里循环只运行一次,因为函数将在循环的第一次迭代中返回单个String。您应该首先将return语句放在循环之外。

def hosts():
    // your code goes here

    for line in stdout.read().splitlines():
        // your code goes here
        hostsIndividual = str(input_line,"utf-8")

    return(hostsIndividual) // returning only one host name

您还需要使用list服务器名称(字符串)并从hosts()方法返回它,而不是仅返回hostIndividual(单个字符串),如下所示。

def hosts():
    // your code goes here

    hosts = []
    for line in stdout.read().splitlines():
        // your code goes here
        hostsIndividual = str(input_line,"utf-8")
        hosts.append(hostsIndividual) 

    return(hosts) // now returning a list of host name

现在,您可以遍历hosts()返回的服务器列表(字符串列表)。

for host in server:
    deploy_key(key, host, username, password)

答案 1 :(得分:1)

您的循环返回单个字符串,即您找到的第一个输入行。 因此,在您的主程序中,服务器是该单个字符串,而您的循环

for host in server:

遍历该字符串的字符。尝试对您的函数循环进行此更改...而不是

for line in ...
    ...
    hostsIndividual = str(input_line,"utf-8")
    return(hostsIndividual)

使用

server_list = []
for line in ...
    ...
    hostsIndividual = str(input_line,"utf-8")
    server_list.append(hostsIndividual)

return(server_list)

这构建了一个字符串列表,每个字符串都是一个服务器; 循环完成后,它将整个列表返回给主程序。