import os
import sys
import time
import pprint
import subprocess
from netaddr import *
print "(1).Ping specific target.\n(2).Ping sweep Subnet.\n(3).Exit"
choice = raw_input("Enter your choice:- ")
if choice == '1':
host = raw_input("Enter IP address to scan: ")
ip = IPAddress("host")
print "accepted"
This is the first part of the program. I'm having problem while accepting an IP address from user as an input.
After executing i get the following error.
Traceback (most recent call last):
File "ping.py", line 13, in <module>
ip = IPAddress("host")
File "/usr/local/lib/python2.7/dist-packages/netaddr/ip/__init__.py", line 308, in __init__
'address from %r' % addr)
netaddr.core.AddrFormatError: failed to detect a valid IP address from 'host'
Using python 2.7.6
You could use a try / except with a loop:
done = False
while not done:
host = raw_input("Enter IP address to scan: ")
try:
ip = IPAddress("host")
done = True
except netaddr.core.AddrFormatError:
print 'Invalid IP Address Format, please try again!'
You are using the string "host" and not the variable host in your assignment.
Change:
ip = IPAddress("host")
to
ip = IPAddress(host)
Related
Paramiko Script is hanging, attempting to ssh through a list of IP address and execute a few commands to extract information that may or may not be there. For example if i was to implement a uname -a it should reveal the hostname, however if the next server in the list doesn't have a hostname then it seems the script is hanging.
import paramiko
import sys
import io
import getpass
import os
import time
# ***** Open Plain Text
f = open("file.txt")
# ***** Read & Store into Variable
hn=(f.read().splitlines())
f.close()
# ***** Credentials
username = raw_input("Please Enter Username: ")
password = getpass.getpass("Please Enter Passwod: ")
# ***** SSH
client=paramiko.SSHClient()
def connect_ssh(hn):
try:
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hn, 22, username, password, look_for_keys=False, allow_agent=False)
print 'Connection Attempting to: '+(hn)
channel = client.get_transport().open_session()
channel.invoke_shell()
#print "CMD
#channel.send("CMD"+"\n")
channel.send("command"+"\n")
CMD = (channel.recv(650000))
print (CMD)
except Exception, e:
print '*** Caught exception: %s: %s' % (e.__class__, e)
try:
channel.close()
except:
pass
# *****Create Loop through input.txt
for x in hn:
connect_ssh(x)
I am trying to learn network scripting via Python. I am trying to extract device names from file "Device_List" and then ssh to the device, executing a command on it and printing the output.
It works fine when I use IP address in the file however it does not if I use a hostname. I tried this on an Ubuntu Trusty as well as Mac OSX.
I get the following error:
FWIP = socket.gethostbyname(name)
socket.gaierror: [Errno -2] Name or service not known
I am able to resolve the hostname on both machines so it is not a DNS issue.
Moreover, if I input the device name from keyboard instead of file, it works fine.
Could you please help me find the issue?
My Code:
import datetime
import paramiko
import socket
import time
import sys
import getpass
with open("Device_List") as dev:
for name in dev:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
Uname = raw_input("Username : ")
Pw = getpass.getpass()
print "Connected to ", name
FWIP = socket.gethostbyname(name)
ssh.connect(FWIP, username=Uname,password=Pw)
remote_conn = ssh.invoke_shell()
remote_conn.send("set cli pager off\n")
sys.stdout.flush()
command = raw_input("Enter Command to run : ")
remote_conn.send(command + "\n")
time.sleep(2)
output = remote_conn.recv(65534)
print output
print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
print "Moving Onto Next Device..."
print "Device List Over"
When you iterate over lines in a text file, e.g. your
with open("Device_List") as dev:
for name in dev:
the default I/O subsystem always includes the '\n' line ending character. One reason is that this way you can tell when a text file ends without ending the final line.
Get used to using (e.g.) dev.rstrip() when you don't want that.
I am telnet into Keysight N1914A power meter and python subprocess.check_out[("Measure:Power?)] is not working. So I am trying to use the python telnetlib. I do not need username or password to log in. IP address and port number is all it needs.
There are lots of examples showing how to log in the device. My question is that how to obtain the results from the device after input commands.
For example: in the device, I type *IDN? it will result its device information; and when I type Measure:Power? it will result the power in decibel format.
import time
import csv
from string import split
import getpass
import sys
import telnetlib
import subprocess
Host = "192.168.1.10"
PORT = 5024
TIMEOUT =10
i = open('practice1.csv', 'wb')
tn = telnetlib.Telnet(Host,PORT)
print "You log in"
time.sleep(5)
while True:
#Powertemp1 = subprocess.check_output(["Measure:Power?"])
#tn.write("Measure:Power?")
tn.write("*IDN?")
Powertemp1 = tn.read_all()
print type(Powertemp1)
print Powertemp1
#Powertemp = float(Powertemp1)
#print '&s' % Powertemp
#wr = csv.writer(i, dialet = 'excel')
#wr.writerow([Powertemp])
time.sleep(5)
type(tn.read_all()) is str, but in the actual screen it is around 40 empty lines, and nothing is stored in the output text file.
Here is the result:
You log in
Traceback (most recent call last):
File "sunlook.py", line 25, in <module>
tn.write("*IDN?")
File "/usr/lib/python2.7/telnetlib.py", line 282, in write
self.sock.sendall(buffer)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 32] Broken pipe
I got this error in my program:
Traceback (most recent call last):
File "scriptA.py", line 17, in <module>
socketPub.bind("tcp://localhost:%s"% portPub)
File "socket.pyx", line 434, in zmq.backend.cython.socket.Socket.bind (zmq/backend/cython/socket.c:3928)
File "checkrc.pxd", line 21, in zmq.backend.cython.checkrc._check_rc (zmq/backend/cython/socket.c:6058)
zmq.error.ZMQError: No such device
This is a simple script I have done to reproduce it:
import zmq
import random
import sys
import time
port = "5566"
if len(sys.argv) > 1:
port = sys.argv[1]
int(port)
portSub = "5556"
context = zmq.Context()
portPub = "5566"
#contextPub = zmq.Context()
socketPub = context.socket(zmq.PUB)
socketPub.bind("tcp://localhost:%s"% portPub)
socket = context.socket(zmq.SUB)
socket.connect("tcp://localhost:%s"% portSub)
socket.setsockopt(zmq.SUBSCRIBE,'')
while True:
socket.send("BB", zmq.SNDMORE)
socket.send("16", zmq.SNDMORE)
socket.send("14", zmq.SNDMORE)
socket.send("11", zmq.SNDMORE)
socket.send("4")
time.sleep(3)
I want to subscribe to one point and be able to send to another one. Is it possible? 2 differents end points. A sends to B and B sends to C.
Try to replace localhost by 127.0.0.1.
For more information, have a look at this stackoverflow thread
Your port numbers do not match. From your code:
portSub = "5556"
portPub = "5566"
So you are binding to one port and connecting to another. Make sure the ports match or simply do:
portSub = "5556"
portPub = portSub
Furthermore, I'm not sure if your binding-string "tcp://localhost:%s"% portPub is correct. When working with ZMQ, I always use the Asterisk * instead of localhost or 127.0.0.1. This always works for me and is something you can try if changing the port number does not make it work: "tcp://*:%s"% portPub (or I prefer f'tcp://*:{portPub}', which is more readable I think). I think you have to use the binding-string I propose. Your connection-string seems to be fine.
I am trying to connect to a remote MySql server from my local machine.
I want to run it whenever the DEBUG constant is set to true.
Here's the script:
import select
import SocketServer
import sys
import threading
import paramiko
SSH_PORT = 22
DEFAULT_PORT = 4000
g_verbose = True
class ForwardServer (SocketServer.ThreadingTCPServer):
daemon_threads = True
allow_reuse_address = True
class Handler (SocketServer.BaseRequestHandler):
def handle(self):
try:
chan = self.ssh_transport.open_channel('direct-tcpip',
(self.chain_host, self.chain_port),
self.request.getpeername())
except Exception, e:
verbose('Incoming request to %s:%d failed: %s' % (self.chain_host,
self.chain_port,
repr(e)))
return
if chan is None:
verbose('Incoming request to %s:%d was rejected by the SSH server.' %
(self.chain_host, self.chain_port))
return
verbose('Connected! Tunnel open %r -> %r -> %r' % (self.request.getpeername(),
chan.getpeername(), (self.chain_host, self.chain_port)))
while True:
r, w, x = select.select([self.request, chan], [], [])
if self.request in r:
data = self.request.recv(1024)
if len(data) == 0:
break
chan.send(data)
if chan in r:
data = chan.recv(1024)
if len(data) == 0:
break
self.request.send(data)
chan.close()
self.request.close()
verbose('Tunnel closed from %r' % (self.request.getpeername(),))
def forward_tunnel(local_port, remote_host, remote_port, transport):
# this is a little convoluted, but lets me configure things for the Handler
# object. (SocketServer doesn't give Handlers any way to access the outer
# server normally.)
class SubHander (Handler):
chain_host = remote_host
chain_port = remote_port
ssh_transport = transport
ForwardServer(('', local_port), SubHander).serve_forever()
def verbose(s):
if g_verbose:
print s
HELP = """\
Set up a forward tunnel across an SSH server, using paramiko. A local port
(given with -p) is forwarded across an SSH session to an address:port from
the SSH server. This is similar to the openssh -L option.
"""
def forward():
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
print 'connecting'
client.connect('*******', username='***', password='****!')
print 'connected'
except Exception, e:
print '*** Failed to connect to %s:%d: %r' % ('*****', 22, e)
sys.exit(1)
try:
forward_tunnel(3306, '127.0.0.1', 3306, client.get_transport())
except SystemExit:
print 'C-c: Port forwarding stopped.'
sys.exit(0)
I have two problems here:
1) I don't know how and when to call my forward function when django raises.
2) When I access django locally and run the script from the console I get the following exception:
exception happened during
processing of request from
('127.0.0.1', 41872) Traceback (most
recent call last): File
"/usr/lib/python2.6/SocketServer.py",
line 558, in process_request_thread
self.finish_request(request, client_address) File
"/usr/lib/python2.6/SocketServer.py",
line 320, in finish_request
self.RequestHandlerClass(request, client_address, self) File
"/usr/lib/python2.6/SocketServer.py",
line 615, in init
self.handle() File "/home/omer/Aptana Studio 3
Workspace/Website/src/ssh_tunnel/tunnel.py",
line 51, in handle
verbose('Tunnel closed from %r' % (self.request.getpeername(),)) File
"", line 1, in getpeername
File "/usr/lib/python2.6/socket.py",
line 165, in _dummy
raise error(EBADF, 'Bad file descriptor') error: [Errno 9] Bad file
descriptor
Was this a bad idea to begin with?
Should I do this manually every time?
I don't think it's a bad idea.
I don't think you need to do it manually.
The exception is a bug in paramiko's forward code sample. This has been addressed by jhalcrow in the pull request here:
https://github.com/paramiko/paramiko/pull/36
This post has some code to do it in a more event driven way, i.e if you wanted to call it via some web event hooks in your django code or the like:
Paramiko SSH Tunnel Shutdown Issue
humm, i didn't try this, but if you are on linux, could you run
ssh -L 3306:localhost:3306 remote.host.ip
through python system call when DEBUG is set?
also if you are on Windows, try putty with port forwarding