阅读';ipconfig';使用Python Pexpect
我在win XP上以SSH服务器的形式运行freeshd,它为经过身份验证的用户返回CMD shell,我希望在运行python脚本时自动发送'ipconfig'命令,连接正常,但我在读取每个字段的结果并将其放入单独的变量时遇到问题,我的代码的结果是“4”,而不是IP地址中的“10'>第一位数字,我不知道数字4是从哪里来的。有什么想法吗 Win XP ipconfig的输出 C:\Documents and Settings\hussam\Desktop>ipconfig阅读';ipconfig';使用Python Pexpect,python,Python,我在win XP上以SSH服务器的形式运行freeshd,它为经过身份验证的用户返回CMD shell,我希望在运行python脚本时自动发送'ipconfig'命令,连接正常,但我在读取每个字段的结果并将其放入单独的变量时遇到问题,我的代码的结果是“4”,而不是IP地址中的“10'>第一位数字,我不知道数字4是从哪里来的。有什么想法吗 Win XP ipconfig的输出 C:\Documents and Settings\hussam\Desktop>ipconfig Windows IP
Windows IP Configuration
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix . :
IP Address. . . . . . . . . . . . : 10.0.2.10
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 10.0.2.15
C:\Documents and Settings\hussam\Desktop>
我的代码
import pexpect
import re
def sendcommand(conn,command):
conn.sendline(command)
conn.expect('\d')
print conn.after
def c(ip,username,password):
global conn
ft = 'ssh '+username+'@'+ip
print 'we are trying to connect to ' + ft
new = 'Are you sure you want to continue connecting'
conn = pexpect.spawn(ft)
result = conn.expect([ pexpect.TIMEOUT , new ,'[P|p]assword:' ])
if result == 0:
print 'connection error'
return
if result == 1:
conn.sendline('yes')
result = conn.expect([ pexpect.TIMEOUT , '[P|p]assword:'])
if result == 0:
print 'connection error'
return
conn.sendline(password)
conn.expect('>')
sendcommand(conn,command)
def main ():
global command
username = 'hkhrais'
ip = '10.0.2.10'
password = 'hkhrais'
command = ' ipconfig'
c(ip,username,password)
main ()
使用起来更简单:
您正在尝试解析ipconfig的输出吗?您的代码在哪里?是的,例如我想把IP地址的结果放在变量x中,子网掩码放在y中,以此类推,其余的代码工作正常,用于启动SSH连接。您用来解析数据的代码在哪里?为什么不使用WinAPI来访问信息,而不是解析用于人类的输出?我需要自动执行此操作,这是完整的代码谢谢您的回复,但我需要知道我的脚本有什么问题。
import wmi
def return_ip_addresses(user,passwd,machine):
i = wmi.WMI(machine, user=user, password=passwd)
addresses = []
for interface in i.Win32_NetworkAdapterConfiguration(IPEnabled=1):
for ip_address in interface.IPAddress:
addresses.append(ip_address)
return addresses
if __name__ == '__main__':
print return_ip_addresses('user','secret','10.1.1.1')