I want to get the client's computername and computer login user in my django project in the intranet. So I use wmi with the ip to get that infomation. However some ip could not be connected by wmi, and come up with an error called "The RPC Server is unavailable". Then I try to use the computername to connect by wmi for testing, it worked. What causes this problem? I have used socket.getnamebyaddr also get the wrong computername.
'''
import wmi
ip = request.META.get('REMOTE_ADDR')
try:
conn = wmi.WMI(computer = ip,user = 'xx', password="xx")
for each in conn.Win32_ComputerSystem():
content = {
'user':json.dumps(each.UserName),
'comname':json.dumps(each.Name),
}
print(each.Name)
print(each.UserName)
'''
Use socket module instead of wmi.
import socket
hostname = socket.gethostname()
ip_address = socket.gethostbyname(hostname)
print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")
More information can be found here
Related
I am trying to find out my ip using socket library in my Django project using this script.
import socket
host_name = socket.gethostname()
ip_address = socket.gethostbyname(host_name)
I get this error:
socket.gaierror: [Errno -2] Name or service not known
Error is pointing to line ip_address = socket.gethostbyname(host_name).
But, I do not get this error while running this same script in terminal.
>>> import socket
>>> hostname = socket.gethostname()
>>> ip = socket.gethostbyname(hostname)
>>>
>>> ip
'192.168.191.5'
This is my /etc/hosts
#127.0.0.1 localhost
#127.0.1.1 softcell-Latitude-3510
# The following lines are desirable for IPv6 capable hosts
#::1 ip6-localhost ip6-loopback
#fe00::0 ip6-localnet
#ff00::0 ip6-mcastprefix
#ff02::1 ip6-allnodes
#ff02::2 ip6-allrouters
I have commented out everything because I want socket to return the System IP.
Why is this not working in Django but giving correct output in Terminal?
I read "python network programming" and got to learn about netmiko. I tried connecting to the Cisco network given in the book and it did not connect. I went online and read other articles on netmiko and tried their Examples using the router login details given in the book, but none of them worked. My internet connection is good (I checked it). Please what is wrong? Is it my location (I stay in Nigeria)?
The error given to me is as follows:
possible reasons why a connection cannot be established are as follows:
*Wrong hostname
*Wrong TCP/IP port
*Wrong password
*Blocked access to router
Please what is wrong, I need help. Or if you have any free router I can connect to just for the sake of learning I would like to know.
If you don't have direct ssh permission and you want to connect through a private server, you can also try paramiko instead of netmiko. Below I wrote an example of connecting via a server and entering the device by typing a command.
import paramiko
import time
from termcolor import colored
from timeit import default_timer as timer
import sys
global password
username = "ldap"
password = "pwd"
def vrf_implement_control(device_ip):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
remote_connection = ssh.connect(device_ip, port="2222", username=username, password=password, timeout=15)
remote_connection = ssh.invoke_shell()
# device_connection
remote_connection.send(" 192.168.0.10\n")
time.sleep(2)
print (colored ("connected_ip_address_"+ device_ip,"blue"))
except Exception as e:
print("erisim yok_\n")
I don't know which sample script you are trying. But as per your error, it looks like there is an issue with device connectivity, You can try to ping the device and check ssh is enabled or not.
Try to run the below script with your credentials, It should work.
from netmiko import ConnectHandler
cisco = {
'device_type': 'cisco_ios', #refer netmiko device type
'host': '10.10.1.1', #Replace with your device ip
'username': 'admin', #Router username
'password': 'cisco123', #password
}
net_connect = ConnectHandler(**cisco)
output = net_connect.send_command("show version")
print(output)
I'm a little over my head when it comes to this SSH thing. Basically I am trying to access a friends server through and SSH tunnel using twisted conch. He has given me the following information:
MONGO_HOST = "ip address"
MONGO_DB = "server name"
MONGO_USER = "user name"
MONGO_PASS = "server password"
I was able to get this information to work using the python library motor.motor_asyncio (I need this be async compatible in order to use with other libraries) but for reasons that I can get into if necessary, will not work on the raspberry pi that I plan on running this program on.
Long story short, I was wondering if anyone could help me with some sample code to access my friends server using the information given above with twisted.conch.
I looked on the twisted.conch readthedocs, but the example needs more information than I can provide (I think) and is WAY over my head in terms of networking/SSH/etc.
Thanks in advance. I am willing to put in the work, but I need to know where to look.
Here is my relevant bit of code so far:
from motor.motor_asyncio import AsyncIOMotorClient
from sshtunnel import SSHTunnelForwarder
MONGO_HOST = "host address"
MONGO_DB = "server name"
MONGO_USER = "username"
MONGO_PASS = "password"
server = SSHTunnelForwarder(
MONGO_HOST,
ssh_username=MONGO_USER,
ssh_password=MONGO_PASS,
remote_bind_address=('address', gate),
local_bind_address=('address', gate)
)
server.start()
client = AsyncIOMotorClient('address', gate)
db = client.server_name
You can forward ports with Conch like this:
rom twisted.internet.defer import Deferred
from twisted.conch.scripts import conch
from twisted.conch.scripts.conch import ClientOptions, SSHConnection
from twisted.conch.client.direct import connect
from twisted.conch.client.default import SSHUserAuthClient, verifyHostKey
from twisted.internet.task import react
def main(reactor):
# authenticate as this user to SSH
user = "sshusername"
# the SSH server address
host = "127.0.0.1"
# the SSH server port number
port = 22
# a local port number to listen on and forward
localListenPort = 12345
# an address to forward to from the remote system
remoteForwardHost = "127.0.0.1"
# and the port number to forward to
remoteForwardPort = 22
conch.options = ClientOptions()
conch.options.parseOptions([
# don't ask the server for a shell
"--noshell",
# set up the local port forward
"--localforward={}:{}:{}".format(
localListenPort,
remoteForwardHost,
remoteForwardPort,
),
# specify the hostname for host key checking
host,
])
# don't stop when the last forwarded connection stops
conch.stopConnection = lambda: None
# do normal-ish authentication - agent, keys, passwords
userAuthObj = SSHUserAuthClient(user, conch.options, SSHConnection())
# create a Deferred that will tell `react` when to stop the reactor
runningIndefinitely = Deferred()
# establish the connection
connecting = connect(
host,
port,
conch.options,
verifyHostKey,
userAuthObj,
)
# only forward errors so the reactor will run forever unless the
# connection attempt fails. note this does not set up reconnection for a
# connection that succeeds and then fails later.
connecting.addErrback(runningIndefinitely.errback)
return runningIndefinitely
# run the reactor, call the main function with it, passing no other args
react(main, [])
Some of the APIs are weird because they are CLI focused. You don't have to do it this way but port forwarding is most easily accessible with these APIs rather than the APIs that are more focused on programmatic use.
Basically, I'm making a Game Server for my Python text-based game. What I want is to let each player make his own local server and/or public server but I don't seem to get it. I've tried this:
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = input("Enter an IP: ")
port = 10922
serversocket.bind((host, port))
But whenever I'm running it and type my own external IP, it throws me this error:
"OSError: [WinError 10049] The requested address is not valid in its context"
Edit: To add to this, it only works with host = "127.0.0.1" but the server isn't public that way.
Can anyone help with this?
The reason it throws this error is because you are binding to an unknown address hence the error.
To bind the socket to your IP, do: socket.gethostbyname(socket.gethostname()) in the place of the address.
socket.gethostname() gets the hostname of the computer e.g. DANS_PC
socket.gethostbyname() looks up the IP of the hostname that is given in the parameters.
To make the server public however, do the same but port forward your computers IP address in your router settings.
I am using server(server_name.corp.com) inside a corporate company. On the server i am running a flask server to listen on 0.0.0.0:5000.
servers are not exposed to outside world but accessible via vpns.
Now when i run host server_name.corp.com in the box i get some ip1(10.*.*.*)
When i run ifconfig in the box it gives me ip2(10.*.*.*).
Also if i run ping server_name.corp.com in same box i get ip2.
Also i can ssh into server with ip1 not ip2
I am able to access the flask server at ip1:5000 but not on ip2:5000.
I am not into networking so fully confused on why there are 2 different ips and why i can access ip1:5000 from browser not ip2:5000.
Also what is equivalent of host command in python ( how to get ip1 from python. I am using socktet.gethostbyname(server_name.corp.com) which gives me ip2)
As far as I can tell, you have some kind of routing configured that allows external connections to the server by hostname (or ip1), but it does not allow connection by ip2. And there is nothing unusual in this. Probably, the system administrator can advise why it is done just like this. Assuming that there are no assynchronous network routes, the following function can help to determine public ip of server:
import socket
def get_ip():
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect(("8.8.8.8", 80))
local_address = sock.getsockname()
sock.close()
local_address = local_address[0]
except OSError:
local_address = socket.gethostbyname(socket.gethostname())
return local_address
Not quite clear about the network status by your statements, I can only tell that if you want to get ip1 by python, you could use standard lib subprocess, which usually be used to execute os command. (See subprocess.Popen)