I'd like to get full path of my directory, something like:
//192.168.1.23/D/test/test/aaaa/
or
//192.168.1.23/D:/test/test/aaaa/
How can I get QFileDialog to give me the IP address of the HDD that I have selected?
Currently using
self.project= str(QtGui.QFileDialog.getExistingDirectory(self, "Select Directory", lastDir))
tried going via os.path.dirname(self.project) but that only ever goes down to D:\
Thanks!
What you want to do is not possible in PyQt directly with QFileDialog what you can do instead is to get the ip address of your machine with another method and then concatenate that with the file path, something like this. QFileDialog isn't 'Network aware'
import socket
def get_ip_addr():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
ip = get_ip_addr()
path = self.project= str(QtGui.QFileDialog.getExistingDirectory(self, "Select Directory", lastDir))
file_path = '//{}/{}'.format(ip, path) # or what ever formatting suits you
You can also take a look at QNetworkInterface http://pyqt.sourceforge.net/Docs/PyQt4/qnetworkinterface.html#interfaceFromName if you're interested in other addresses on your machine, but the example above just returns the ip address that's used to route to 8.8.8.8
Not sure where I found it but here is the option I followed at the end. I let user decide then which device to use for location
from netifaces import interfaces, ifaddresses, AF_INET
p =[]
for ifaceName in interfaces():
addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]
p.append(ifaceName.join(addresses))
print p[0],p[1]
print p
Related
I have a samba directory smb://172.16.0.10/public_pictures/ and I would like to know if it is accessible.
try something like the following:
import urllib
if open("smb://172.16.0.10/public_pictures/"):
print("accessible")
else:
print("no accessible")
but obviously it does not work for me
Using pysmb (docs):
from smb.SMBConnection import SMBConnection
remote_address = "172.16.0.10"
share_name = "public_pictures"
conn = SMBConnection(username, password, name, remote_name)
conn.connect(remote_address)
accessible = share_name in conn.listShares()
One way of handling samba is to use pysmb. If so, then it goes something like the following:
# we need to provide localhost name to samba
hostname = socket.gethostname()
local_host = (hostname.split('.')[0] if hostname
else "SMB{:d}".format(os.getpid()))
# make a connection
cn = SMBConnection(
<username>, <password>, local_host, <netbios_server_name>,
domain=<domain>, use_ntlm_v2=<use_ntlm_v2>,
is_direct_tcp=<self.is_direct_tcp>)
# connect
if not cn.connect(<remote_host>, <remote_port>):
raise IOError
# working connection ... to check if a directory exists, ask for its attrs
attrs = cn.getAttributes(<shared_folder_name>, <path>, timeout=30)
Some notes:
in your example above, public_pictures is the shared folder, while path would be simply /
you'll need to know if you are using SMB on port 139 or 445 (or a custom port). If the latter you will usually want to pass is_direct_tcp=True (although some servers will still serve NetBIOS samba on 445)
if you expect not to need a username or password, then probably you are expecting to connect as username="guest" with an empty password.
This might be a something simple here, but I'm still learning python.
Basically I'm trying to pull an IP address from a hostname, which works fine, but if the host does not resolve it errors. I have it now so that once it resolves the IP address it populates it to a text box, so what i'm trying to do here is if it fails to resolve... To put a message in that text box saying no host found or whatever. I get an error: "socket.gaierror: [Errno 11004] getaddrinfo failed" when it does not resolve.
This is the code i have:
def findip():
host = hname.get() # Pulls host from text box1
ip = gethostbyname(host)
ipaddress.set(ip) #exports to text box2
return
So what i don't know is the If command needed for the failure (if that makes any sense) it would be something like:
if "gethostbyname fails"
ipaddress.set("Host does not resolve")
else
ipaddress.set(ip)
You have to try and catch the exception, this way:
def findip():
host = hname.get()
try:
ip = gethostbyname(host)
except socket.gaierror:
ip = "Host does not resolve"
ipaddress.set(ip)
Just make sure you have the socket module imported or it won't work, if you have no need for the socket module you can import the the exception only, so you need to do either of these:
import socket
import socket.gaierror
I am very new to Python. So in newboston's latest python tutorial Im making a web crawler. This Python script however only works on Linux. What would be the windows alternative to the following code?
import os
def get_ip_address(url):
command = "host " + url
process = os.popen(command)
results = str(process.read())
marker = results.find('has address') + 12
return results[marker:].splitlines()[0]
print(get_ip_address('google.com'))
I want it in the same format as I want to code multiple modules(i.e. get ip, who is etc.) and put them together as one Python program.
I am trying to obtain ONLY the ip address and nothing else in the results.
Alternatively, This is what I have for Windows so far:
import socket
def get_ips_for_host(url):
try:
ips = socket.gethostbyname_ex(url)
except socket.gaierror:
ips = []
return ips
ips = get_ips_for_host('www.facebook.com')
print(repr(ips))
How can i modify it to make it get only the IP address?
Similarly how can I get the nmap scan and the 'who is'?
the_ip = get_ips_for_host('www.facebook.com')[-1][0]
What's the most Pythonic way to create a list of the addressable IP addresses given a netaddr IPRange or netaddr IPNetwork.
If I use these, then it includes subnet and broadcast addresses:
hosts = list(IPRange('212.55.64.0','212.55.127.255'))
hosts = IPNetwork('192.168.0.1/24')
So what I need for say IPNetwork(192.168.0.0/27) is a list from 192.168.0.1 to 192.168.0.31 note that 192.168.0.0 and 192.168.0.32 must not be included.
EDIT
Thanks for info on how to do it with IPy. Does anybody know if it can be done with netaddr?
The following is a quick script to do what you want using netaddr
(Python 2.7, linux)
from netaddr import *
def addr(address, prefix):
ip = IPNetwork(address)
ip.prefixlen = int(prefix)
return ip
myip = addr('192.168.0.0', '27')
for usable in myip.iter_hosts():
print '%s' % usable
After doing a bit of research I found this way:
l = list(netaddr.IPNetwork('192.168.0.0/27').iter_hosts())
On my linux machine, 1 of 3 network interfaces may be actually connected to the internet. I need to get the IP address of the currently connected interface, keeping in mind that my other 2 interfaces may be assigned IP addresses, just not be connected.
I can just ping a website through each of my interfaces to determine which one has connectivity, but I'd like to get this faster than waiting for a ping time out. And I'd like to not have to rely on an external website being up.
Update:
All my interfaces may have ip addresses and gateways. This is for an embedded device. So we allow the user to choose between say eth0 and eth1. But if there's no connection on the interface that the user tells us to use, we fall back to say eth2 which (in theory) will always work.
So what I need to do is first check if the user's selection is connected and if so return that IP. Otherwise I need to get the ip of eth2. I can get the IPs of the interfaces just fine, it's just determining which one is actually connected.
If the default gateway for the system is reliable, then grab that from the output from route -n the line that contains " UG " (note the spaces) will also contain the IP of the gateway and interface name of the active interface.
the solution is here : http://code.activestate.com/recipes/439093-get-names-of-all-up-network-interfaces-linux-only/
import fcntl
import array
import struct
import socket
import platform
"""
global constants. If you don't like 'em here,
move 'em inside the function definition.
"""
SIOCGIFCONF = 0x8912
MAXBYTES = 8096
def localifs():
"""
Used to get a list of the up interfaces and associated IP addresses
on this machine (linux only).
Returns:
List of interface tuples. Each tuple consists of
(interface name, interface IP)
"""
global SIOCGIFCONF
global MAXBYTES
arch = platform.architecture()[0]
# I really don't know what to call these right now
var1 = -1
var2 = -1
if arch == '32bit':
var1 = 32
var2 = 32
elif arch == '64bit':
var1 = 16
var2 = 40
else:
raise OSError("Unknown architecture: %s" % arch)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
names = array.array('B', '\0' * MAXBYTES)
outbytes = struct.unpack('iL', fcntl.ioctl(
sock.fileno(),
SIOCGIFCONF,
struct.pack('iL', MAXBYTES, names.buffer_info()[0])
))[0]
namestr = names.tostring()
return [(namestr[i:i+var1].split('\0', 1)[0], socket.inet_ntoa(namestr[i+20:i+24])) \
for i in xrange(0, outbytes, var2)]
print localifs()