首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Python-Pexpect读取'ipconfig‘

使用Python-Pexpect读取'ipconfig‘
EN

Stack Overflow用户
提问于 2013-02-24 01:58:32
回答 1查看 1.7K关注 0票数 0

我在win XP上运行freeSSHd作为SSH服务器,它为经过身份验证的用户返回CMD shell,当我运行python脚本时,我想得到自动发送'ipconfig‘命令的结果,我让连接正常工作,但我有一个问题,读取每个字段的结果并将其放在单独的变量中,我的代码的结果是'4’而不是'10‘> IP地址中的第一个数字,我不知道数字4来自哪里。有什么想法吗?

Win XP ipconfig的输出

C:\Documents和Settings\hussam\Desktop>ipconfig

代码语言:javascript
复制
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>

我的代码

代码语言:javascript
复制
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 ()
EN

回答 1

Stack Overflow用户

发布于 2013-02-24 02:40:07

使用WMI的方法更简单

代码语言:javascript
复制
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')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15043694

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档