首页 > 代码库 > py3.5 telnet的实例(在远程机器上批量创建用户)

py3.5 telnet的实例(在远程机器上批量创建用户)

import sys
import telnetlib
import time

HOST = ["172.18.217.12","172.18.217.13"]#往后一直加即可

USER = "username"

PASSWORD = "password"

command1 = "net user test 1 /add" #添加用户

command2 = "net localgroup administrators test /add"  #给将用户添加到组

wait_time = 1

for host in HOST:

  tn = telnetlib.Telnet(host,timeout = 10)
  #tn.read_eager().decode(‘utf-8‘)

  tn.read_until(b‘login:‘)
  tn.write(USER.encode(‘utf-8‘) + "\r".encode(‘utf-8‘))
  time.sleep(wait_time)
  #tn.read_very_eager().decode(‘utf-8‘)
  
  time.sleep(wait_time)
  #tn.read_until(b‘ Administrator\n\rpassword: ‘)
  tn.write(PASSWORD.encode(‘utf-8‘) + "\r".encode(‘utf-8‘))

  time.sleep(wait_time)
  tn.read_very_eager().decode(‘utf-8‘) #这句话的意思只是读取信息,但是撤掉就不能运行成功,不知原因,前面的如果不用read_until,全部用sleep的方法,则注掉的read_very_eager都要加上才能成功

  tn.write(command1.encode(‘utf-8‘) + "\r".encode(‘utf-8‘))
  time.sleep(wait_time)

  tn.write(command2.encode(‘utf-8‘) + "\r".encode(‘utf-8‘))
  time.sleep(wait_time)

  a = tn.read_very_eager()
  tn.close()
  print(host + a.decode(‘gbk‘))
  print(‘\n‘)

解决了挨个建用户、加组的问题,所以一些用法并没有深究,这里的转码非常繁琐,而且,\n没能执行成功 \r才可以

py3.5 telnet的实例(在远程机器上批量创建用户)