如何遍历每个IP地址列表和SSH?

时间:2020-10-02 13:41:06

标签: python-3.x raspberry-pi

我是python的新手。我有一个带有默认凭据的Raspberry Pi设备列表(文本文件)。我想连接到每个服务器,登录并更改密码。我可以使用以下代码对单个设备执行此操作:

import os
import socket
from ssh2.session import Session

host = '172.16.1.119'
user = 'pi'
passw = 'raspberry'

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect ((host, 22))

session = Session()
session.handshake(sock)
session.userauth_password(user, passw)

channel = session.open_session()
channel.shell()
channel.write("echo raspberry | sudo -S su && echo 'pi:newpwhere' | sudo chpasswd\n")
channel.write("exit\n")

size, data = channel.read()

while size > 0:
        print(data.decode())
        size, data = channel.read()

print ("Exit status: {0}".format(channel.get_exit_status()))

当我尝试使用类似的代码来读取具有多个IP地址的文件并执行相同的操作时,会收到错误消息:

import os
import socket
from ssh2.session import Session

user = 'pi'
passw = 'raspberry'
file =  input("please select the file that contains the hosts: ")

with open(file) as f:
    hosts = f.readlines()

def chgpw():
    channel = session.open_session()
    channel.shell()
    channel.write("echo raspberry | sudo -S su && echo 'pi:newpwhere' | sudo chpasswd\n")
    channel.write("exit\n")

for i in hosts:
    print(i)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((i,22))
    session = Session()
    session.handshake(sock)
    session.userauth_password(user, passw)
    chgpw()

print ("Exit status: {0}".format(channel.get_exit_status()))

我收到的错误是:

Traceback (most recent call last):
  File "stack-ov.py", line 21, in <module>
    sock.connect((i,22))
socket.gaierror: [Errno -2] Name or service not known

print语句print(i)确实在第21行发生错误之前就打印出列表中的第一个IP地址。

1 个答案:

答案 0 :(得分:0)

readlines在返回的每一行中都包含换行符。使用前,您需要先rstrip i

for i in hosts:
    stripped = i.rstrip()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((stripped, 22))

换行符使每个地址无效。