【问题标题】:Python string format with symbols in password密码中带有符号的 Python 字符串格式
【发布时间】:2015-11-13 08:58:35
【问题描述】:

目标:我想通过 SSH 连接到交换机并执行从源到目标的跟踪路由。交换机上用于认证的源地址和目的地址以及用户名和密码由用户输入并存储在变量中。我正在使用 Python 2.7.10

工作代码:

from Exscript.util.start import start

from Exscript import Host, Account

from netaddr import *          

src_addr = raw_input('Enter source address for trace:   ')

SrcAddr = IPAddress(src_addr)     

dest_addr = raw_input('Enter destination address for trace: ')    

DesAddr = IPAddress(dest_addr)     

def do_something(job, host, conn):

    conn.execute('terminal length 0')
    conn.execute('tr {}'.format(DesAddr))

account1 = Account('username', 'password')  # <<<< THIS <<<<

host1 = Host('ssh://{}'.format(SrcAddr))

host1.set_account(account1)

start(account1, host1, do_something)

问题代码:

from Exscript.util.start import start

from Exscript import Host, Account

from netaddr import *          

src_addr = raw_input('Enter source address for trace:   ')

SrcAddr = IPAddress(src_addr)       #function for IP address

dest_addr = raw_input('Enter destination address for trace: ')    

DesAddr = IPAddress(dest_addr)     #function for IP address

user_name = raw_input('Enter your CEC username:  ')

pswd = raw_input('Enter your password:  ')

def do_something(job, host, conn):

    conn.execute('terminal length 0')
    conn.execute('tr {}'.format(DesAddr))

account1 = Account('{}', '{}'.format(user_name, pswd))  # <<<< THIS <<<<

host1 = Host('ssh://{}'.format(SrcAddr))

host1.set_account(account1)

start(account1, host1, do_something)

我在“工作”和“问题”代码示例中注释了重点代码。在“工作”示例下,如果我对用户名和密码进行硬编码,它将成功通过交换机进行身份验证。在“问题”代码示例下,我尝试使用 format() 以便用户可以将凭据输入到变量中。但由于某种原因,它不会使用此方法进行身份验证。我怀疑这是因为密码包含“!”符号,但我不确定。

总结

验证成功的代码

account1 = Account('username', 'password')

未验证的代码

account1 = Account('{}', '{}'.format(user_name, pswd))

【问题讨论】:

  • 您的帖子不包含问题。通常,没有明确问题的帖子会导致答案混乱。 您有具体问题吗?
  • Account('{}'.format(user_name), '{}'.format(pswd)),虽然我不知道你为什么不做Account(user_name, pswd)

标签: python ssh passwords format


【解决方案1】:

在您问题的这一行中:

account1 = Account('{}', '{}'.format(user_name, pswd))

您只是格式化其中一个字符串。试试这个:

account1 = Account('{}'.format(user_name), '{}'.format(pswd))

或者,等价甚至更简单:

account1 = Account(user_name, pswd)

【讨论】:

  • 感谢您的回复。这两个建议都有效:account1 = Account(user_name, pswd) account1 = Account(‘{}’.format(user_name), ‘{}’.format(pswd))
【解决方案2】:

我认为您没有正确使用格式说明符。

试试

account1 = Account("'{}','{}'".format(user_name,pswd))

【讨论】:

    猜你喜欢
    • 2015-11-05
    • 2014-11-04
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多