【问题标题】:Python3 pass variable to paramikoPython3将变量传递给paramiko
【发布时间】:2022-01-24 05:54:46
【问题描述】:

所以我从 1.1.1.0 到 1.1.1.10 范围内获取所有 ip,并使用每个 ip 单独连接到 ssh。当我运行“print(host1)”时,它给了我 ip,但是当我在 ssh.connect 中使用变量 host1 时,我收到错误“getaddrinfo() argument 1 must be string or None”,如果我将变量 host1 放入引号中我收到错误“只能将 str(不是“IPv4Address”)连接到 str”

    start_ip = ipaddress.IPv4Address('1.1.1.0')
    end_ip = ipaddress.IPv4Address('1.1.1.10')
    for ip_int in range(int(start_ip), int(end_ip)):
    host1 = ipaddress.IPv4Address(ip_int)
    print(ipaddress.IPv4Address(ip_int))
    print(host1)
    def ssh_connect(password, code=0):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        try:
            ssh.connect(host1, port=22, username=username, password=password, timeout=5)

【问题讨论】:

  • 尝试将 'print(host1)' 语句移到 'try:' 语句下方,我的直觉是你不会得到你期望的输出。

标签: python-3.x ssh


【解决方案1】:

Python 依赖于选项卡。因此,当您编写控制结构时,您必须小心这一点。缩进告诉 Python 哪些语句应该包含在你的循环中。我的建议是删除函数定义,直到你让这段代码工作,然后如果你想在以后更好地了解 Python 时概括该功能,最好有一段有效的代码而不是一段你没有的代码' t 完全掌握。但行首的间距用于指示控制结构的范围。在开始使用 Python 编码之前,我从未见过这一点,这对我来说是最难掌握的。看起来你可能也遇到了麻烦。

如果您查找子标题“将 IP 地址与其他模块一起使用”,您会发现您必须使用 str(...)IPv4Address 返回的主机名类型转换为字符串

https://docs.python.org/3/howto/ipaddress.html

【讨论】:

  • 是的,只要我输入 host1 = str(ipaddress.IPv4Address(ip_int) 就可以了。为什么 IP 必须是字符串?IP 中的句点是否使它成为程序无法读取的地方如果它不是一个字符串,还是不能读取 ipaddress.ipv4address 部分?感谢您的帮助。
  • 这只是标准符号。
猜你喜欢
  • 2014-12-10
  • 1970-01-01
  • 1970-01-01
  • 2019-05-08
  • 2020-01-24
  • 2018-10-11
  • 2012-02-13
  • 2014-09-05
  • 2011-10-13
相关资源
最近更新 更多