Masking OS / PC name in Python - python

I'm using various commands in Python to get the PC names:
platform.node()
socket.gethostname()
os.environ['COMPUTERNAME']
Is it possible to "mask" or "spoof" your PC name so that these commands get a pre-defined name? (not the real PC name)

As stated in the SMTPLIB doc :
class smtplib.SMTP(host='', port=0, local_hostname=None, [timeout, ]source_address=None) :
…
If specified, local_hostname is used as the FQDN of the local host in the HELO/EHLO command. Otherwise, the local hostname is found using socket.getfqdn()

Related

How do i get the IP address of ORACLE 11 g DATABASE on windows 10 to remotely connect to it?

I have installed oracle 11g on windows 10 f drive of my laptop. I want know the IP address of the database in order to connect to it using python? How do i find the ip address?
I tried this command:
select sys_context('USERENV','IP_ADDRESS') from dual;
however it gives me the local host address.
i also tried
SELECT UTL_INADDR.get_host_address from dual;
however this throws an error saying network access denied by access control list
how do i find out the IP address?
There is no IP Address assigned to the Oracle database. In your case, The database is installed on your own machine so the IP ADDRESS of the database is the same as the IP ADDRESS of your own machine.
select sys_context('USERENV','IP_ADDRESS') from dual;
The aforementioned query gives the IP ADDRESS of the client which is connected to the database. I think you are misunderstood by this one - It is not the database' IP ADDRESS.
If you need the HOST_NAME of the database then you can use the following query. Note that HOAST_NAME can be used to connect to the database in the connection string or in TNS_NAMES.ora
SQL> SELECT INSTANCE_NAME, HOST_NAME FROM V$INSTANCE;
INSTANCE_N HOST_NAME
---------- --------------------
orcl DESKTOP-0******
SQL>
I hope it will clear all your doubts.
Cheers!!
You must have a TNSNAMES.ORA file in your Oracle Configuration. Find that file and open it. There should be ip adresses and needed ports in there.
From official docs:
By default, tnsnames.ora is located in the $ORACLE_HOME/network/admin
directory on UNIX operating systems and in the
%ORACLE_HOME%\network\admin directory on Windows operating systems.
tnsnames.ora can also be stored the following locations:
The directory specified by the TNS_ADMIN environment variable or
registry value
On UNIX operating systems, the global configuration directory. For
example, on the Solaris Operating System, this directory is
/var/opt/oracle.
Then you can connect db with python cx_Oracle library using syntax below for connection string.
connection_oracle_textfile.txt -> username/password#HOST:PORT/SERVICE_NAME(you can find all of them but username and password in tnsnames.ora file)
import cx_Oracle as cx_Oracle
def get_oracle_table_from_dbm(sql_text):
if 'connection_oracle' not in globals():
print('connection does not exist. Try to connect it...')
f = open('connection_oracle_textfile.txt', "r")
fx = f.read()
####
global connection_oracle
connection_oracle = cx_Oracle.connect(fx)
####
print('connection established!!')
print('Already have connection. Just fetch data!!')
return pd.read_sql(sql_text, con=connection_oracle)
Docs

How to access a different/remote Windows machine using Python?

I am currenlty using machine A and I am trying to access machine B via Python to copy files from machine B to machine A.
I have already tried the methods explained here How to connect to a remote Windows machine to execute commands using python? , but with no luck as I cannot manage to even get access to the remote machine.
I am open to other solutions, even better if using Python 3+.
Here is an example of the code in use.
ip = r'\\IP.IP.IP.IP'
username = r'AccountUserName'
password = r'AccountPassword'
# -------------------------------- with win32net
import win32net
import win32file
data = {
'remote': r'\\IP.IP.IP.IP\C$',
'local': 'C:',
'username': username,
'password': password
}
win32net.NetUseAdd(None, 2, data)
# -------------------------------- with wmi
import wmi
from socket import *
try:
print ("Establishing connection to %s" %ip)
connection = wmi.WMI(ip, user=username, password=password )
print ("Connection established")
except wmi.x_wmi:
print ("Your Username and Password of "+getfqdn(ip)+" are wrong.")
Using the win32net method
According to the documentation here https://learn.microsoft.com/en-us/windows/win32/api/lmuse/nf-lmuse-netuseadd
If the function is to be run from the same computer the script is running from (A), then the first parameter f NetUseAdd can be left to NONE, but with that I get the error
pywintypes.error: (87, 'NetUseAdd', 'The parameter is incorrect.')
Whilst if I change it with "127.0.0.1" I get the error
pywintypes.error: (50, 'NetUseAdd', 'The request is not supported.')
And lastly, if I change it with the same IP that I am trying to access I get the error
pywintypes.error: (1326, 'NetUseAdd', 'Logon failure: unknown user name or bad password.')
Using the wmi method
It gives the error
Your Username and Password of \\IP.IP.IP.IP are wrong.
There can be multiple ways to achieve this. One of them is given below which makes use of inbuilt windows utilities.
import os
machine_b = {"ip":"10.197.145.244","user":"administrator","pwd":"abc1234"}
src = r"C:\Temp" # folder to copy from remote machine
dest = r"C:\Python27\build\temp" # destination folder on host machine
network_drive_letter = "Z:"
source_driver_letter = os.path.splitdrive(src)[0][0]
cmd = "netuse %s \\%s\%s$ %s /u:%s"%(network_drive_letter, machine_b["ip"],source_driver_letter,machine_b["pwd"],machine_b["user"])
os.system(cmd)
cmd = "robocopy %s %s /mir"%(src.replace(source_driver_letter,network_drive_letter),dest)
os.system(cmd)
You can improve this code by handling exceptions and replacing os.system with subprocess.Popen calls.
Note: Be careful with /MIR switch as it can copy as well as delete files in the host machine. It creates mirror of destination folder.

check if samba directory exist in python3

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.

PyQT QFileDialog - get full directory including IP of disk

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

Webdriver connected to selenium-server:4444 a through proxy

When I run (WinXP OS, Python 2.7)
wd = webdriver.Remote (command_executor = 'http://127.0.0.1:4444/hub', desired_capabilities = webdriver.DesiredCapabilities.INTERNETEXPLORER)
in my system there is a proxy server by default, and is connected to selenium-server:4444 a through proxy. How to make that connection went directly to selenium-server:4444.
It is a bit late, but I stumbled over the same problem today and solved it, so for the next one who searches, here is the solution:
The system proxy settings are fetched from the *_proxy windows environment variables (http_proxy, https_proxy, ftp_proxy, ...), so if you have a company proxy defined there it will be used.
Add a new environment variable in windows options or, if you use intelliJ IDEA, in the Run configuration settings:
no_proxy=localhost,127.0.0.1
The reason you will find in python-2.7.6/Lib/urllib.py, around line 1387:
def proxy_bypass_environment(host):
"""Test if proxies should not be used for a particular host.
Checks the environment for a variable named no_proxy, which should
be a list of DNS suffixes separated by commas, or '*' for all hosts.
"""
no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
# '*' is special case for always bypass
if no_proxy == '*':
return 1
# strip port off host
hostonly, port = splitport(host)
# check if the host ends with any of the DNS suffixes
no_proxy_list = [proxy.strip() for proxy in no_proxy.split(',')]
for name in no_proxy_list:
if name and (hostonly.endswith(name) or host.endswith(name)):
return 1
# otherwise, don't bypass
return 0

Categories

Resources