整数到字符串在同一个 Python 程序中的转换



嗨,我正在尝试使用此程序中的整数 ipaddress。 但我需要在response = os.system("ping -c 1 " + hostname + "-I" + str(mystring))中将其称为字符串

#!/usr/bin/python
import os
interface = os.system("ifconfig ge1 | grep UP")
ip = os.system("ifconfig ge1.1 | grep UP")
ipaddress = os.system("ifconfig ge1 | grep 'inet addr:' | cut -d: -f2 |  awk '{ print $1}'")
print ipaddress
mystring = repr(ipaddress)
print mystring
if interface == 0:
 print interface, ' interface is UP!'
 hostname = "8.8.8.8"
 response = os.system("ping -c 1 " + hostname + "-I" + str(mystring))
 if response == 0:
  print hostname, 'is up!'
 else:
   print hostname, 'is down!'
else:
   print interface, ' interface is down!'

os.system("ifconfig ge1 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'")不会返回给您的IP地址,而是返回退出状态代码,因此您需要使用一个模块来获取接口的IP地址(eth0,WLAN0.)。等),

正如@stark链接评论所建议的那样,使用netifaces包或套接字模块,示例取自这篇文章:

import netifaces as ni
ni.ifaddresses('eth0')
ip = ni.ifaddresses('eth0')[2][0]['addr']
print ip

====

====================================================================================
import socket
import fcntl
import struct
def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])
get_ip_address('eth0')

编辑-1:

建议您通过子进程而不是 os.system 运行终端命令,因为我读过它更安全。

现在,如果您想将ip_address的结果传递到ping命令中,我们开始:

import subprocess
import socket
import fcntl
import struct
def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

hostname = "8.8.8.8"
cmdping = "ping -c 1 " + hostname + " -I " + get_ip_address('eth0')
p = subprocess.Popen(cmdping, shell=True, stderr=subprocess.PIPE)
#The following while loop is meant to get you the output in real time, not to wait for the process to finish until then print the output.
while True:
    out = p.stderr.read(1)
    if out == '' and p.poll() != None:
        break
    if out != '':
        sys.stdout.write(out)
        sys.stdout.flush()

相关内容

  • 没有找到相关文章

最新更新