Handling telnet timeout/connection refused in pexpect python router - python-2.7

I am trying to write a script where I need to ssh multiple jump server to access a router.
e.g LocalMachine----ssh---server1---ssh---server2---telnet/ssh---router
Not sure what is the best way of doing it, i tried achieving it through pexpect.
My requirement is when i telnet from server server2 to router and it timeout/connection refused i want try ssh
any suggestions please?
import time, pexpect
child = pexpect.spawn('ssh username#server-1') ##########ssh to 1st Jump server
child.expect('password: ')
child.sendline('abc')
child.expect('$')
child.sendline('ssh username#server-2') ##########ssh to 2nd Jump server
print child.before
child.expect('password:')
child.sendline('xyz')
child.expect('$')
print child.before
host=raw_input("Enter Router name: ")
try:
print "Trying Telnet ", host
child.sendline(' telnet ' + host) ### router telnet at this point i want if telnet is timeout/connection refused try ssh
print child.before
except pexpect.TIMEOUT:
print child.before
else:
child.expect(':')
child.sendline("User")
child.expect(":")
child.sendline('passwprd')
child.expect('#')
child.sendline("\n")
child.expect("#")
finally:
print "Trying SSH ", host
child.sendline(' ssh -l User ' + host)
print child.before
child.expect(":")
child.sendline('password')
child.expect('#')
child.sendline("\n")
print child.before
child.interact()

The pexpect.TIMEOUT exception would be raised by the program instance running on your machine. It does not know if there is a timeout for the telnet instance running on the remote machine that you have ssh'ed to. The only way you can see if the telnet connection has a timeout or similar error, ie. connection refused, is to look at the output from the the process through pexpect. If you look at the documentation for expect it says that you can give a list of conditions - this could be one way to go.
For example:
index = p.expect (['timeout', 'connection refused]) # Fill in correct words :)

Related

Python smtp set up with gmail fails

try:
server = smtplib.SMTP("smtp.gmail.com:587")
server.ehlo()
except Exception as t:
print 'setup failed'
print t
Gives the error:
[Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
using socks and setting a proxy fixed the issue

Gremlin remote command fails with timeout error: Host did not respond in a timely fashion

I connected to a remote gremlin server via gremlin groovy shell. Connection succeeded. But for any remote command I try to execute it gives timeout error. Even for command :> 1+1
gremlin> :remote connect tinkerpop.server conf/senthil.yaml
==>Connected - 10.40.40.65/10.40.40.65:50080
gremlin> :> 1+1
Host did not respond in a timely fashion - check the server status and submit again.
Display stack trace? [yN]
org.apache.tinkerpop.gremlin.groovy.plugin.RemoteException: Host did not respond in a timely fashion - check the server status and submit again.
at org.apache.tinkerpop.gremlin.console.groovy.plugin.DriverRemoteAcceptor.submit(DriverRemoteAcceptor.java:120)
at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
at org.apache.tinkerpop.gremlin.console.commands.SubmitCommand.execute(SubmitCommand.groovy:41)
at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
at org.codehaus.groovy.tools.shell.Shell.execute(Shell.groovy:101)
at org.codehaus.groovy.tools.shell.Groovysh.super$2$execute(Groovysh.groovy)
at sun.reflect.GeneratedMethodAccessor14.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
This is my conf file: remote.yaml
hosts: [10.40.40.65]
port: 50080
serializer: { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0, config: { serializeResultToString: true }}
I'm using dynamodb + titan.
You might not have a truly successful connection. The console (and underlying driver) is optimistic in that it really doesn't fail a connection until a request is sent as it expects the server may come online "later". I would go back to investigating if the server is running, if you have the right IP, if the host property is not set to something like "localhost" if you are connecting remotely, if the port is open, that you are using a compatible version of TinkerPop, etc.

Celery, mechanize and socks proxy

I'm working on a project that needs to access a webpage using mechanize with a socks proxy. After digging a bit, I came up with the following code:
def create_connection(address, timeout=None, source_address=None):
sock = socks.socksocket()
sock.connect(address)
return sock
CRAWLER_SOCKS_PROXY_HOST = '0.0.0.0'
CRAWLER_SOCKS_PROXY_PORT = 1080
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, CRAWLER_SOCKS_PROXY_HOST, CRAWLER_SOCKS_PROXY_PORT)
socket.socket = socks.socksocket
socket.create_connection = create_connection
Which indeed allows me to access the webpage using the proxy socks I created with the ssh -f -N -D 1080 user#host.
After doing that, I realized that Celery couldn't connect to my Redis broker giving Connection closed unexpectedly errors so I killed the ssh process and confirmed that the proxy socks configuration was the culprit. The error obtained is: Cannot connect to redis://127.0.0.1:6379//: Error connecting to SOCKS5 proxy 0.0.0.0:1080: [Errno 111] Connection refused.
So, my question is: Is there a way to set a proxy socks for mechanize but without affecting the other parts of the code? I suspect that if I try to use requests module, it will also use the proxy which is not my intention. I just want the proxy for a specific call.
I solved this by putting the
CRAWLER_SOCKS_PROXY_HOST = '0.0.0.0'
CRAWLER_SOCKS_PROXY_PORT = 1080
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, CRAWLER_SOCKS_PROXY_HOST, CRAWLER_SOCKS_PROXY_PORT)
socket.socket = socks.socksocket
socket.create_connection = create_connection
lines inside the function call (where I needed to do the call using proxy socks) rather than in the global scope of the module. This way seems Celery can connect to the broker (and also reconnect after quitting and launching again).

how to get nova client (v1.1) to use ssh tunnel when retrieving server list

the openstack nova client is giving me fits. i can't figure out how to get it to use a local ssh tunnel url i specify instead of the one it retrieves. so:
from novaclient.v1_1 import client as nova_client
from pprint import pprint
self.__nova_client = nova_client.Client(
'myusername',
'mypassword',
'mytenantname',
'https://localhost:5443/v2.0',
service_type='compute',
insecure=True
)
for server in self.__nova_client.servers.list():
pprint(server)
yields...
requests.exceptions.ConnectionError: HTTPConnectionPool(host='os-compute.vip.mysubdomain.mydomain.com', port=8774): Max retries exceeded with url: /v2/aa0dffecaef543aca072a26fdff5c92b/servers/detail (Caused by <class 'socket.error'>: [Errno 111] Connection refused)
because the "os-compute.vip.mysubdomain.mydomain.com:8774" address is unreachable from where the script is running.
the self.__nova_client = nova_client.Client() bit connects fine because it uses 'https://localhost:5443/v2.0' - the established tunnel i provide. i just need a way to override the "os-compute.vip.mysubdomain.mydomain.com:8774" that it's trying to connect to with a "localhost:8774" tunnel that i set up. but i can't figure out whether/how that's possible.
any guidance will be greatly appreciated.
Your nova client is pulling the service catalogue from keystone through the tunnel setup on your localhost. You will need to explicitly override the endpoint specified in the service catalogue.
One way is to explicitly specify the endpoint, while some of the clients allow you to directly specify the endpoint on construction novaclient doesn't, take a look at nova_client.management_url after you've constructed the object and replace it with your localhost address.

Exception Error Errorno 10061 in solrpy program

I just started working on solrpy with below code.
import solr
# create a connection to a solr server
s = solr.SolrConnection('http://localhost:8083/solr')
# add a document to the index
s.add(id=1, title='Lucene in Action', author=['Erik Hatcher', 'Otis Gospodnetic'])
s.commit()
# do a search
response = s.query('title:lucene')
for hit in response.results:
print hit['title']
it is throwing Socket error: Errno 10061. Can anyone please help me in resolving this issue.
TCP Error 10061 means No connection could be made because the target machine actively refused it. So you have to check the program can connect localhost:8083. Checking your Jetty or other web container (ex. tomcat).