Programmatically Connect to Wifi device python Raspberry - python-2.7

I am working with Raspberry PI 3.
Here I have a task to create Custom GUI to view all the available wifi connections and to connect selected wifi using python.
I am able to get all the Wifi connections through following code.
import subprocess
results = subprocess.check_output(["netsh", "wlan", "show", "network"])
print(results)
results = results.decode("ascii") # needed in python 3
results = results.replace("\r","")
ls = results.split("\n")
ls = ls[4:]
ssids = []
x = 0
while x < len(ls):
if x % 5 == 0:
ssids.append(ls[x])
x += 1
#print(ssids)
But, I am not able to get apis to connect to particular wifi.
Kindly provide me good tutorial for that If any.
Thank you guys

Related

Unable to query VMs on vcenter server appliance using pyvmomi

I am getting the following error when trying to use pyvmomi to get a list of VMs from the vcenter server appliance.
pyVmomi.VmomiSupport.vim.fault.NoPermission: (vim.fault.NoPermission) {
dynamicType = <unset>,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'Permission to perform this operation was denied.',
faultCause = <unset>,
faultMessage = (vmodl.LocalizableMessage) [],
object = 'vim.Folder:group-d1',
privilegeId = 'System.View',
missingPrivileges = (vim.fault.NoPermission.EntityPrivileges) [
(vim.fault.NoPermission.EntityPrivileges) {
dynamicType = <unset>,
dynamicProperty = (vmodl.DynamicProperty) [],
entity = 'vim.Folder:group-d1',
privilegeIds = (str) [
'System.View'
]
}
]
}
This is my python code :
import atexit
import ssl
from pyVim import connect
from pyVmomi import vim
import pdb
def vconnect(hostIP,port=None):
if (True):
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE # disable our certificate checking for lab
else:
context = ssl.create_default_context()
context.options |= ssl.OP_NO_TLSv1_3
#cipher = 'DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:ECDHE-ECDSA-AES128-GCM-SHA256'
#context.set_ciphers(cipher)
pdb.set_trace()
if (port):
service_instance = connect.SmartConnect(host=str(hostIP), # build python connection to vSphere
user="root",
pwd="HagsLoff#1324",
port=port,
sslContext=context)
else:
service_instance = connect.SmartConnect(host=str(hostIP), # build python connection to vSphere
user="root",
pwd="HagsLoff#1324",
sslContext=context)
atexit.register(connect.Disconnect, service_instance) # build disconnect logic
content = service_instance.RetrieveContent()
container = content.rootFolder # starting point to look into
viewType = [vim.VirtualMachine] # object types to look for
recursive = True # whether we should look into it recursively
containerView = content.viewManager.CreateContainerView(container, viewType, recursive) # create container view
children = containerView.view
for child in children: # for each statement to iterate all names of VMs in the environment
summary = child.summary
print(summary.config.name)
# connecting to ESX host
vconnect("192.168.160.160")
# connecting to vcsa VM
vconnect("192.168.160.170", 443)
So I am using a nested ESX that runs on my workstation 16. I have deployed the vcsa on this ESX host via the windows CLI installer. Querying the ESX host works fine whereas querying the vcenter server appliance (vcsa) gives me the above error.
I looked at this discussion which talks about setting 'global permissions'; however on my vcenter server management VM, my 'administration' tab does not look anything like this:
What it instead looks like is this:
So apparently I have a 'vcenter server management' appliance and not what is referred to as the 'vsphere client'.
So with this context set, I have some questions:
Is the error above due to my trial license?
How is the 'vcenter server management (vcsa)' appliance different from the 'vsphere client'?
Is it possible to change 'global permissions' on the vcsa or do I need to get the 'vsphere client' to do that?
I tried adding the default port (443) as mentioned here to no avail. Keen to hear from you soon

How to solve "tensorflow.python.framework.errors_impl.AbortedError : RecvTensor expects a different device incarnation" in Tensorflow

I am trying to distribute a simple Tensorflow computation into two machines in Amazon AWS.
I am running the following program with the command line argument 0 and 1 in machine 1 and machine 2, respectively. I am getting the following error: tensorflow.python.framework.errors_impl.AbortedError : RecvTensor expects a different device incarnation...Your worker job ... was probably restarted. Check your worker job for the reason why it was restarted. However, I haven't restarted the Machine 2.
I used ping and nc to make sure that Machine 2 is indeed listening in the designated port.
import tensorflow as tf
import numpy as np
import sys
config = tf.ConfigProto(log_device_placement=True)
task_number = int(sys.argv[1])
cluster = tf.train.ClusterSpec({"local": ["localhost:2222", "<private_ip_of_machine_2>:2222"]})
server = tf.train.Server(cluster, job_name="local", task_index=task_number, config=config, start=True)
print("Starting server #{}".format(task_number))
tf.reset_default_graph()
r = 2
c = 2
if task_number == 0:
with tf.device('/job:local/task:0'):
v = tf.Variable(np.random.normal(0, 1, size=(r, c)), name="v")
with tf.device('/job:local/task:1'):
w = tf.matmul(v, v, name="w")
with tf.device('/job:local/task:0'):
sum = tf.reduce_sum(w, name="sum")
sess = tf.Session("grpc://localhost:2222")
print("Session Run Start")
sess.run(tf.global_variables_initializer())
print("Res: ", sess.run(sum))
LOGDIR = "./tf_board_square/"
writer = tf.summary.FileWriter(LOGDIR, sess.graph)
#writer.add_graph(sess.graph)
else:
server.join()
The program works in localhost with the tasks running in different ports.
Actually, the cluster specification was incorrectly defined. Instead of localhost, I had to specify the IP address of Machine 1 in the spec. Otherwise, Machine 2 has no way to know the address of Machine 1. Hence, I believe, each tf server needs to know the address of all the other servers.
cluster = tf.train.ClusterSpec({"local": ["ip_of_machine_2:2222", "<ip_of_machine_2>:2222"]})

How to insert compressed byte message on IBM MQ using python? (I've tried PYMQI and Spring Python)

I'm testing an application which accepts the compressed messages over IBM MQ. This requires me to send compressed (.zip) message on IBM MQ with custom jms property as Compressed = Y
I am struggling with 2 issues -
How to load a .zip message in _IBMMQ
Set the header or _jms property as Compressed = 'Y'
I've tried, via Python
(1) pymqi- I was able to send a string over MQ.
But unable to send a .zip till now.
(2) Spring Python - With this I was able to set the custom property as Compressed Y, but again stuck with loading the .zip into Queue.
#PYMQI
import pymqi
queue_manager = 'QM1'
channel = 'DEV.APP.SVRCONN'
host = '127.0.0.1'
port = '1414'
queue_name = 'TEST.1'
message = 'Hello from Python!'
conn_info = '%s(%s)' % (host, port)
qmgr = pymqi.connect(queue_manager, channel, conn_info)
queue = pymqi.Queue(qmgr, queue_name)
queue.put(message)
queue.close()
qmgr.disconnect()
# Spring Python
from springpython.jms.core import TextMessage
msg = TextMessage("Hello!")
msg.Compressed = "Y"
print msg
from springpython.jms.core import JmsTemplate
from springpython.jms.factory import WebSphereMQConnectionFactory
qm_name = "QM.1"
channel = "SVRCONN1.1"
host = "192.168.1.121"
listener_port = "1434"
queue1 = "TEST.1"
factory = WebSphereMQConnectionFactory(qm_name, channel, host,
listener_port)
jms_template = JmsTemplate(factory)
jms_template.send(msg, queue1)
factory.destroy()
#Above code is for reference only, I have taken them from their own websites.

How to get MAC address of connected Access point?

I am using Scapy to sniff access point(AP) beacon packets and also getting all AP beacon packets and it's MAC address nearby AP but I need exact MAC address of connected AP then How to sniff only connected AP beacon frame or How to filter connected AP beacon frame using scapy or any alternate idea.
*I am doing it in python 2.7
Assuming the beacon frame is called pkt. pkt.addr1 is the destination MAC, pkt.addr2 is the source MAC and pkt.addr3 is the MAC address of the AP. You could write something like:
from scapy.all import *
def ap_mac(pkt):
if pkt.haslayer(Dot11)
if pkt.type == 0 and pkt.subtype == 8:
print('SSID: '+%s+' MAC:'+%s)(pk.info,pkt.addr3)
else: pass
else: pass
sniff(prn=ap_mac)
to print out all the AP MACs from beacon frames. Then you could use something like:
from scapy.all import *
def sniff_ap(pkt):
if pkt.haslayer(Dot11):
if pkt.add3 == 'xx.xx.xx.xx.xx.xx': ## AP MAC
print(pkt.summary())
else: pass
else: pass
sniff(prn=sniff_ap)
Here is a good link re: beacon frames. https://www.4armed.com/blog/forging-wifi-beacon-frames-using-scapy/
I choose alternate method i.e using command in python program
Code snippet
def Check_connected_ap():
cmd =["nmcli -f BSSID,ACTIVE dev wifi list | awk '$2 ~ /yes/ {print $1}'"]
address = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
(out, err) = address.communicate()
print out

How to find vm in particular folder using pyvmomi

Hi I am new in python and I am exploring pyvmomi. Here I want to fetch vm info.Like I have one data center i.e "DataCenter1"
In that data center there are two folders LinuxServer and WindowsServer these folder contains vms.So I want to fetch vm name with their respective folder names
DataCenter1
|
|----LinuxServer
| |---RHEL-VM
| |---Ubuntu-VM
|
|----WindowsServer
| |---win2k12r2-VM
| |---win2k8r2-VM
My code:
from pyvim.connect import SmartConnect, Disconnect
import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_NONE
connect = SmartConnect(host="172.0.0.0",user="root",pwd="****",port=int("443"),sslContext=context)
datacenter = connect.content.rootFolder.childEntity[0]
print (datacenter)
vms = datacenter.vmFolder.childEntity
for i in vms:
print(i.name)
#Here I want to fetch vm name and their respective folder names
Disconnect(c)
Here I am able to fetch all vm names but I want to fetch folder name of respective vm.
Is there any method ?
Can you please guide me.
Here you will get parent name of that vm means i.e your folder name if it exist.
from pyvim.connect import SmartConnect, Disconnect
import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_NONE
connect = SmartConnect(host="172.0.0.0",user="root",pwd="****",port=int("443"),sslContext=context)
datacenter = connect.content.rootFolder.childEntity[0]
print (datacenter)
vms = datacenter.vmFolder.childEntity
for vm in vms:
print(vm.parent.name)
Disconnect(c)
I use python3.6, full example below. It implement login vsphere and print every virtual machine name.
#!/usr/bin/env python3.6
# encoding: utf-8
from pyVim import connect
import ssl
def login():
ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
ssl_context.verify_mode = ssl.CERT_NONE
si = connect.SmartConnect(host='192.168.0.1', user='root', pwd='password',
sslContext=ssl_context)
print(si)
print('\nHello World!\n')
print('If you got here, you authenticted into vCenter.')
data_center = si.content.rootFolder.childEntity[0]
vms = data_center.vmFolder.childEntity
for vm in vms:
print(vm.name)
if __name__ == '__main__':
login()
result:
'vim.ServiceInstance:ServiceInstance'
Hello World!
If you got here, you authenticted into vCenter.
sclautoesxd12v03
sclautoesxd12v04
sclautoesxd12v07
sclautoesxd12v09
sclautoesxd12v11
sclautoesxd12v12
sclautoesxd12v13
sclautoesxd12v16
sclautoesxd12v17
sclautoesxd12v01
sclautoesxd12v02
sclautoesxd12v05
sclautoesxd12v06
sclautoesxd12v08
sclautoesxd12v10
sclautoesxd12v14
sclautoesxd12v15