How to get VNC port number using libvirt? - vnc

I set autoport=yes in a domain's("virtual machine" in libvirt) config file so the VNC port is assigned automatically in the run time.
I need to get this port so I can connect to the vm from outside, but I can't find the proper API to do so. Better in python because I'm using the libvirt-python bindings.

I have not found any API for the VNC port, not sure if the newer version of libvirt has this interface?
However, you can use the command virsh vncdisplay $domainName to show the port. NOTE: you must modify /etc/libvirt/qemu.conf enable vnc_listen='0.0.0.0'.

There's no API to get the VNC port. You have to take and parse the XML file to find out that port. Of course if the guest is destroyed (powered off/offline) that port will be a value of -1.
char * virDomainGetXMLDesc (virDomainPtr domain, unsigned int flags)
<domain>
<devices>
<graphics type='vnc' port='5900' autoport='yes'/>
</devices>
</domain>
References
http://libvirt.org/html/libvirt-libvirt.html#virDomainGetXMLDesc

Here's how you do it in python, in case anyone needs this.
Save as vncport.py
from xml.etree import ElementTree as ET
import sys
import libvirt
conn = libvirt.open()
domain = conn.lookupByName(sys.argv[1])
#get the XML description of the VM
vmXml = domain.XMLDesc(0)
root = ET.fromstring(vmXml)
#get the VNC port
graphics = root.find('./devices/graphics')
port = graphics.get('port')
print port
Run Command
python vncport.py <domain name>

Here is one for the PHP version, if anyone needs this:
$res = libvirt_domain_lookup_by_name($conn, $domname);
$xmlString = libvirt_domain_get_xml_desc($res, '');
$xml = simplexml_load_string($xmlString);
$json = json_encode($xml);
$data = json_decode($json,TRUE);
$port = intval($data["devices"]["graphics"]["#attributes"]["port"]);

Related

Network sniffer that opens the ips as tabs in browser?

I'm trying to write a code that basically grabs the network traffic sniffed by wireshark and opens the ips in tabs in selenium.
At first I tried using whois and socket.gethostbyaddr() as All I needed was to translate the ips to domains. But it didn't workout well.
I ran into a problem with permissions because pyshark needs root privilege and selenium doesn't work as root.
here is the code:
import pyshark
from selenium import webdriver
global ips
ips = ''
options = webdriver.ChromeOptions()
options.headless = False
options.add_argument("user-data-dir=/home/afterlife/Documents/chrome_profiles/cyber")
browser = webdriver.Chrome(executable_path='/home/afterlife/Downloads/chromedriver', options=options)
def get_domain_name(ip_address):
for line in ips:
if ip_address not in line:
ips += ip_address+'\n'
browser.execute_script('''window.open(''' + ip_address + ''',"_blank");''')
capture = pyshark.LiveCapture(interface="wlp1s0")
capture.set_debug()
for packet in capture.sniff_continuously():
try:
if hasattr(packet, 'http'):
protocol = packet.transport_layer
source_address = packet.ip.src
source_port = packet[packet.transport_layer].srcport
destination_address = packet.ip.dst
destination_port = packet[packet.transport_layer].dstport
print(destination_address)
get_domain_name(destination_address)
except:
print("exception")
I tried to make pyshark work as non root but failed, I used sudo dpkg-reconfigure wireshark-common but it haven't effected tshark of pyshark.
I also tried using os.setuid() which I successfully used once but forgot/now it doesn't work. I used 0 for root and 1000 for my non-root user.
How would you accomplish what I want?
Thank you!

How to get a file from a server in a cluster in Vsphere using pyVmomi to remote(host) pc

I am able to execute a command inside the server but I want to get that output in my local pc. I don't want want to use ssh keys. I want to use just the host's username and password as well as vm's(server's) username and password. I couldn't find a direct method to get the shell output of server in my pc, but this method seems half done like generate and save the output in server and then get the file from server. I am finding it difficult to get file(sample.txt) from server to local host(pc).
[EDIT: I am able to do this using via via method(Store the output to server and then get it back into local pc, is there a direct method ?) ]
from pyVim import connect
from config import *
from pyVmomi import vim, vmodl
import ssl
service_instance = connect.SmartConnect(host="yyyyyyy", port=some_number,user="xxx" , pwd=pwd,sslContext=ssl._create_unverified_context())
content = service_instance.RetrieveContent()
vm = searcher.FindByIp(ip="zzzzzz", vmSearch=True)
creds = vim.vm.guest.NamePasswordAuthentication(username='root', password=vmpwd)
pm = service_instance.content.guestOperationsManager.processManager
#checks python version and stores in sample.txt in server
ps = vim.vm.guest.ProcessManager.ProgramSpec(programPath='/usr/bin/python', arguments='--version &> sample.txt')
res = pm.StartProgramInGuest(vm, creds, ps)
print(res) #Prints pid
This does the job but I would appreciate if someone knows how to directly get the output of shell command from server to my local pc. This code makes a file with the output of cmd inside the server and it gets copied into my local pc
from pyVim import connect
from config import *
from pyVmomi import vim, vmodl
import ssl
import os
import requests
service_instance = connect.SmartConnect(host="xxxx", port=aaa,user="yyy" , pwd=pwd,sslContext=ssl._create_unverified_context())
content = service_instance.RetrieveContent()
# # Find a VM
vm = searcher.FindByIp(ip="aaaa", vmSearch=True)
creds = vim.vm.guest.NamePasswordAuthentication(username='root', password=vmpwd)
pm = service_instance.content.guestOperationsManager.processManager
#executes and saves sample.txt into server
ps = vim.vm.guest.ProcessManager.ProgramSpec(programPath='/usr/bin/python', arguments='--version &> sample.txt')
res = pm.StartProgramInGuest(vm, creds, ps)
dest="/Users/username/Desktop/vcenter/sample.txt" #My local pc
src="/root/sample.txt" #Server's directory
fti = content.guestOperationsManager.fileManager.InitiateFileTransferFromGuest(vm, creds, src)
resp=requests.get(fti.url, verify=False)
#Writes into file
with open(dest, 'wb') as f:
f.write(resp.content)

RabbitMQ Over SSL

I'm trying to set RabbitMQ to work over SSL.
I have changed the configuration file (/etc/rabbitmq/rabbitmq.config) as mentioned in the following link
https://www.rabbitmq.com/ssl.html to:
# Defaults to rabbit. This can be useful if you want to run more than one node
# per machine - RABBITMQ_NODENAME should be unique per erlang-node-and-machine
# combination. See the clustering on a single machine guide for details:
# http://www.rabbitmq.com/clustering.html#single-machine
#NODENAME=rabbit
# By default RabbitMQ will bind to all interfaces, on IPv4 and IPv6 if
# available. Set this if you only want to bind to one network interface or#
# address family.
#NODE_IP_ADDRESS=127.0.0.1
# Defaults to 5672.
#NODE_PORT=5672
listeners.ssl.default = 5671
ssl_options.cacertfile = /home/myuser/rootca.crt
ssl_options.certfile = /home/myuser/mydomain.com.crt
ssl_options.keyfile = /home/myuser/mydomain.com.key
ssl_options.verify = verify_peer
ssl_options.password = 1234
ssl_options.fail_if_no_peer_cert = false
I keep getting the following errors:
sudo rabbitmq-server
/usr/lib/rabbitmq/bin/rabbitmq-server: 15: /etc/rabbitmq/rabbitmq-env.conf: listeners.ssl.default: not found
If I remove the above line I get the following error:
sudo rabbitmq-server
/usr/lib/rabbitmq/bin/rabbitmq-server: 17: /etc/rabbitmq/rabbitmq-env.conf: ssl_options.cacertfile: not found
It is worth to mention that without the above, SSL configuration, everything works just fine.
Could you please assist?
Thanks :)
It's very important when you request assistance with software that you always state what version of the software you're using. In the case of RabbitMQ, providing the Erlang version and operating system used is also necessary.
In your case, you have (commented-out) environment configuration in /etc/rabbitmq/rabbitmq-env.conf, as well as RabbitMQ configuration, which is not correct. The following lines must be removed from rabbitmq-env.conf and put into the /etc/rabbitmq/rabbitmq.conf file:
listeners.ssl.default = 5671
ssl_options.cacertfile = /home/myuser/rootca.crt
ssl_options.certfile = /home/myuser/mydomain.com.crt
ssl_options.keyfile = /home/myuser/mydomain.com.key
ssl_options.verify = verify_peer
ssl_options.password = 1234
ssl_options.fail_if_no_peer_cert = false
Please also see the documentation
NOTE: the RabbitMQ team monitors the rabbitmq-users mailing list and only sometimes answers questions on StackOverflow.
in the Rabbitmq.config change the following to listen on 5673
listeners.ssl.default = 5673

Controlling a minecraft server with python

I've searched a lot for this and have not yet found a definitive solution. The closest thing I've found is this:
import shutil
from os.path import join
import os
import time
import sys
minecraft_dir = ('server diectory')
world_dir = ('server world driectory')
def server_command(cmd):
os.system('screen -S -X stuff "{}\015"'.format(cmd))
on = "1"
while True:
command=input()
command=command.lower()
if on == "1":
if command==("start"):
os.chdir(minecraft_dir)
os.system('"C:\Program Files\Java\jre1.8.0_111\bin\java.exe" -Xms4G -Xmx4G -jar craftbukkit-1.10.2.jar nogui java')
print("Server started.")
on = "0"
else:
server_command(command)
When I launch this program and type 'start' the CMD flashes up and closes instantly. Instead I want the CMD to stay open with the minecraft sever running from it. I'm not sure why this happens or what the problem is, any help would be greatly appreciated.
p.s. I have edited this to my needs (such as removing a backup script that was unnecessary) but it didn't work before. The original link is: https://github.com/tschuy/minecraft-server-control
os.system will simply run the command then return to your python script with no way to further communicate with it.
On the other hand using subprocess.Popen gives you access to the process while it runs, including writing to it's .stdin which is how you send data to the server:
def server_command(cmd):
process.stdin.write(cmd+"\n") #just write the command to the input stream
process = None
executable = '"C:\Program Files\Java\jre1.8.0_111\bin\java.exe" -Xms4G -Xmx4G -jar craftbukkit-1.10.2.jar nogui java'
while True:
command=input()
command=command.lower()
if process is not None:
if command==("start"):
os.chdir(minecraft_dir)
process = subprocess.Popen(executable, stdin=subprocess.PIPE)
print("Server started.")
else:
server_command(command)
you can also pass stdout=subprocess.PIPE so you can also read it's output and stderr=subprocess.PIPE to read from it's error stream (if any)
As well instead of process.stdin.write(cmd+"\n") you could also use the file optional parameter of the print function, so this:
print(cmd, file=process.stdin)
Will write the data to process.stdin formatted in the same way that print normally does, like ending with newline for you unless passing end= to override it etc.
Both of the above answers do not work in the environment I tried them in.
I think the best way is to use RCON, not sending keys to a window.
RCON is the protocol used by games to run commands.
Many python libraries support Minecraft RCON, and the default server.properties file has an option for RCON.
We will use the python module: MCRON.
Install it. It works for windows, mac, linux.
Type:
pip install mcrcon
Lets configure your server to allow RCON.
In server.properties, find the line 'enable-rcon' and make it look like this:
enable-rcon=true
Restart and stop your server.
Find the line 'rcon.password' and set it to any password you will remember.
You can leave the port default at 25575.
Now, open your terminal and type:
mcron localhost
Or your server ip.
You will be prompted to enter the password you set.
Then you can run commands and will get the result.
But we are doing this with python, not the PYPI MCRON scripts - so do this.
from mcrcon import MCRcon as r
with r('localhost', 'insertyourpasswordhere') as mcr:
resp = mcr.command('/list')
print(resp) #there are 0/20 players online: - This will be different for you.

Unable to run python cgi scripts using CGIHTTPRequestHandler in Python 3.3

I am a noob; trying to create and use a simple webserver in Python that executes CGI scripts written in Python. I am using Windows XP and Python v3.3.0. I have a "myserver" directory which contains "myserver.py","sample.html" and the directory "cgi-bin" which in turn contains "cgi_demo.py"
myserver.py
from http.server import HTTPServer
from http.server import CGIHTTPRequestHandler
port = 8080
host = '127.0.0.1'
server_address = (host,port)
httpd = HTTPServer(server_address,CGIHTTPRequestHandler)
print("Starting my web server on port "+str(port))
httpd.serve_forever()
cgi_demo.py
import cgi
import cgitb; cgitb.enable()
print("Content-type: text/html")
print
print("<html><body>")
for i in range(0,100):
print(i,"<br>")
print("</body></html>")
Now the directory listing works fine for "myserver" but not for "cgi-bin"; maybe that is how it is coded - I don't have a problem here. "sample.html" is retrieved fine too. However, the execution of "cgi_demo.py" is not proper. I get a blank page in the browser; and the console window (which is blank too) appears and disappears. Moreover, on the server's console I get the message
127.0.0.1 - - [29/Nov/2012 12:00:31] "GET /cgi-bin/cgi_demo.py HTTP/1.1" 200 -
127.0.0.1 - - [29/Nov/2012 12:00:31] command: C:\Python33\python.exe -u "D:\python apps\my web server\cgi-bin\cgi_demo.py" ""
127.0.0.1 - - [29/Nov/2012 12:00:32] CGI script exited OK
Please tell me what is wrong! I get the feeling that the output stream of my script is not connected to the server. What am I doing wrong? Don't say that I have to extend CGIHTTPRequestHandler!!
SORRY for the trouble!
Well, it is my fault. 2 things to note:
[1]The console window that appeared and disappeared; it only happens when I use IDLE to execute the server. If the script is already running in a normal windows console then this does not happen. My Feeling was WRONG.
[2]There is an bug/error in my cgi script. After printing the HTTP header; the print statement that I wrote was just "print" instead of actually being "print()".This is so embarrassing! But, even then why didn't the interpreter catch this error?

Resources