I am trying to do a slack integration for my bot. this is my python script that will run the bot on slack:
from rasa_core.channels import HttpInputChannel
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter
from rasa_slack_connector import SlackInput
nlu_interpreter = RasaNLUInterpreter('./model/nlu/default/weathernlu')
agent = Agent.load('./model/dialogue', interpreter = nlu_interpreter)
input_channel = SlackInput('*******', #app verification token
'*******', # bot verification token
'********', # slack verification token
True)
agent.handle_channel(HttpInputChannel(5006, '/', input_channel))
My problem is everytime I close the app and try to run it, i can't use the same port. I started with 5000 and you can see I reached 5006 because I had to change it everytime. If I try to run it using the same port I get this error:
OSError: [WinError 10048] Only one usage of each socket address
(protocol/networ k address/port) is normally permitted
Can anyone explain what's going on?
You should check which port are binded using the cmd netstat and also check the process still running on your machine.
Closing your app might not kill the process therefore your previous instance of your app may still use the ports.
Related
I am currently underway with my Senior Capstone project, in which I am to write a somewhat basic program which allows a custom interface on my iPhone6 device to remotely control or issue critical commands to a NIDS (Suricata) established at my home RaspberryPi(3B+) VPN. My question, however, is whether it's feasible to write said program which can allow remote access control of basic functions/response options on the Pi's IDS, given that I am utilizing it as a device within the VPN network. The main issue would be establish remote signaling to the iOS device whenever there is an anomaly and allowing it to respond back and execute root-level commands on the NIDS.
If it is of any good use, I am currently using Pythonista as a runtime environment on my mobile device and have set my VPN's connection methods to UDP, but I'm not sure if enabling SSH would assist me. I have a rather basic understanding of how to operate programming in regards to network connectivity. I very much appreciate any and all the help given!
from tkinter import *
window=Tk()
window.geometry("450x450")
window.title("IDS Response Manager")
label1=Label(window,text="Intrusion Response Options",fg= 'black',bg ='white',relief="solid",font=("times new roman",12,"bold"))
label1.pack()
button1=Button(window,text="Terminate Session",fg='white', bg='brown',relief=RIDGE,font=("arial",12,"bold"))
button1.place(x=50,y=110) #GROOVE ,RIDGE ,SUNKEN ,RAISED
button2=Button(window,text="Packet Dump",fg='white', bg='brown',relief=RIDGE,font=("arial",12,"bold"))
button2.place(x=220,y=110) #GROOVE ,RIDGE ,SUNKEN ,RAISED
button3=Button(window,text="Block Port",fg='white', bg='brown',relief=RIDGE,font=("arial",12,"bold"))
button3.place(x=110,y=170) #GROOVE ,RIDGE ,SUNKEN ,RAISED
Very basic options as are shown here.
You can use a flask server with an API, which you can send post requests to. You can then send get requests to receive the commands. To host your API, look at Heroku (free tier available, and very much functional, with already configured app_name.herokuapp.com).
Search up to send a post request with the technologies you are using to build your app. Send keyword command with the command to the /send_commands along with the password, "password_here" (changeable to anything you want).
Python:
Modules: Flask (server), request (client)
Server Code:
from flask import Flask
app = Flask(__name__)
commands = []
#app.route('/get_commands', methods=['GET'])
def get_commands():
tmp_commands = commands[::]
commands = []
return {'commands': tmp_commands}
#app.route('/send_commands', methods=['POST'])
def send_commands():
if request.json['password'] == "password_here":
commands.append(request.json['command'])
return {'worked': True}
else:
return {'worked': False}
if __name__ == '__main__':
app.run(debug=True)
Client Code:
import requests
URL = "url_here/get_commands"
commands = requests.get(url = URL)
for command in commands:
os.system(command)
My requirement is ability to run a PowerShell script on a Windows 2012 server remotely, this has to be triggered from a Linux server using Python script.
Need suggestions on best way to handle this and also sample code (if possible).
Below are the steps I intend to achieve but i see it's not working as expected.
PowerShell scripts to be executed are already placed in Windows server (2012).
Python3 program running on Linux (CentOS) does SSH to Windows server (2012) using netmiko module.
sends the command (PowerShell command to execute script in remote Windows server) over the SSH connection.
I was able to connect to the remote Windows server using Python. But I don't see this method working as expected.
Need an effective and efficient way to achieve this.
from netmiko import ConnectHandler
device = ConnectHandler(device_type="terminal_server",
ip="X.X.X.x",
username="username",
password="password")
hostname = device.find_prompt()
output = device.send_command("ipconfig")
print (hostname)
print (output)
device.disconnect()
Nothing much is done for 'terminal_server" device type. You have to do manual passing at the moment.
Below is extracted from COMMON_ISSUES.md
Does Netmiko support connecting via a terminal server?
There is a 'terminal_server' device_type that basically does nothing post SSH connect. This means you have to manually handle the interaction with the terminal server to connect to the end device. After you are fully connected to the end network device, you can then 'redispatch' and Netmiko will behave normally
from __future__ import unicode_literals, print_function
import time
from netmiko import ConnectHandler, redispatch
net_connect = ConnectHandler(
device_type='terminal_server', # Notice 'terminal_server' here
ip='10.10.10.10',
username='admin',
password='admin123',
secret='secret123')
# Manually handle interaction in the Terminal Server
# (fictional example, but hopefully you see the pattern)
# Send Enter a Couple of Times
net_connect.write_channel("\r\n")
time.sleep(1)
net_connect.write_channel("\r\n")
time.sleep(1)
output = net_connect.read_channel()
print(output) # Should hopefully see the terminal server prompt
# Login to end device from terminal server
net_connect.write_channel("connect 1\r\n")
time.sleep(1)
# Manually handle the Username and Password
max_loops = 10
i = 1
while i <= max_loops:
output = net_connect.read_channel()
if 'Username' in output:
net_connect.write_channel(net_connect.username + '\r\n')
time.sleep(1)
output = net_connect.read_channel()
# Search for password pattern / send password
if 'Password' in output:
net_connect.write_channel(net_connect.password + '\r\n')
time.sleep(.5)
output = net_connect.read_channel()
# Did we successfully login
if '>' in output or '#' in output:
break
net_connect.write_channel('\r\n')
time.sleep(.5)
i += 1
# We are now logged into the end device
# Dynamically reset the class back to the proper Netmiko class
redispatch(net_connect, device_type='cisco_ios')
# Now just do your normal Netmiko operations
new_output = net_connect.send_command("show ip int brief")
I am trying to ssh to a test cisco router in a test environment using python paramiko, and run cisco commands in that test router.
Everything works great except for 1 small detail.
After running the script I want the ssh session to remain open. (so I can run other commands manually).
I want to keep the ssh session open until I type "exit"
I found another link with a similar issue but I cant understand the solution.
(See here Python ssh - keep connection open after script terminates)
I would appreciate if someone can help me out here
My code
import paramiko
import time
def ssh_session(ip):
try:
session = paramiko.SSHClient() #Open the session
session.set_missing_host_key_policy(paramiko.AutoAddPolicy())
session.connect(ip, username = "ciscouser1", password = "password")
connection = session.invoke_shell()
####Running Cisco IOS commands###
connection.send("enable\n")
connection.send("password1") #sending
connection.send("\n")
connection.send("configure terminal\n\n")
time.sleep(1)
connection.send("do show ip int brief\n")
time.sleep(1)
except paramiko.AuthenticationException:
print "wrong credentials"
ssh_session("10.10.10.1")
The session timeout would be controlled by the SSH server. To the best of my knowledge, the only way to keep your session alive on the client side is to not be inactive, which can be accomplished by sending null packets. As to how to do this specifically with paramiko I am not certain. Perhaps you could send some kind of dummy command (or maybe even an empty string?) every so often?
I'm building a tester for a Python script which performs works with a RethinkDB database. As part of the setUp() method, I'm trying to make the tester start up the RethinkDB server on localhost on port 28016 in case that has not yet been done.
I'm using subprocess to start the server. The problem is that, according to https://docs.python.org/2/library/subprocess.html, subprocess waits for the command to complete. In this case, it seems that as long as the server is up and running, the process is not complete and testing does not continue beyond the setUp() stage.
Here is the script I'm trying:
import unittest
import rethinkdb as r
import subprocess
class TestController(unittest.TestCase):
HOST = "localhost"
PORT_OFFSET = 1
PORT = 28015 + PORT_OFFSET
DB = "ipercron"
TABLE = "sensor_data"
def setUp(self):
try:
self.conn = r.connect(self.HOST, self.PORT)
except r.ReqlDriverError:
print("The RethinkDB server is not yet ready. Starting it up...")
subprocess.call(["rethinkdb", "--port-offset", str(TestController.PORT_OFFSET)])
self.conn = r.connect(self.HOST, self.PORT)
if TestController.DB not in r.db_list().run(self.conn):
r.db_create(TestController.DB).run(self.conn)
self.conn.use(TestController.DB)
if TestController.TABLE not in r.table_list().run(self.conn):
r.table_create(TestController.TABLE).run(self.conn) # Create the table if it does not yet exist
r.table(TestController.TABLE).delete().run(self.conn) # Empty the table to start with a clean slate
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
suite = unittest.TestLoader().loadTestsFromTestCase(TestController)
unittest.TextTestRunner(verbosity=2).run(suite)
The subprocess is meant to perform the rethinkdb --port-offset 1 command at the command line and then continue with the script. However, when I run the script I get the usual message that the server is ready:
kurt#kurt-ThinkPad:~/dev/clones/ipercron-compose/controller$ python unittest_controller.py
test_upper (__main__.TestController) ... The RethinkDB server is not yet ready. Starting it up...
Running rethinkdb 2.3.5~0xenial (GCC 5.3.1)...
Running on Linux 4.4.0-42-generic x86_64
Loading data from directory /home/kurt/dev/clones/ipercron-compose/controller/rethinkdb_data
Listening for intracluster connections on port 29016
Listening for client driver connections on port 28016
Listening for administrative HTTP connections on port 8081
Listening on cluster addresses: 127.0.0.1, 127.0.1.1, ::1
Listening on driver addresses: 127.0.0.1, 127.0.1.1, ::1
Listening on http addresses: 127.0.0.1, 127.0.1.1, ::1
To fully expose RethinkDB on the network, bind to all addresses by running rethinkdb with the `--bind all` command line option.
Server ready, "kurt_ThinkPad_a0k" 07bb35f6-3a33-4e8b-9e9c-a78504457969
Without any further action. How can I make the unittest proceed with the testing?
The problem is as you said, that subprocess.call is blocking and will wait for the command to finish. For scenarios where you need to spawn a child process without waiting for it to finish, you can use subprocess.Popen:
process = subprocess.Popen(["rethinkdb", "--port-offset", str(TestController.PORT_OFFSET)])
This gives you back a Popen object that provides a whole bunch of very useful methods to communicate with the child process. For example, you will probably want to use process.kill() in your unit test's tearDown() function to shut down your database.
Try with the following code
subprocess.call(["rethinkdb", "--port-offset", str(TestController.PORT_OFFSET)], shell = True)
#import ssh
import socket
from fabric.operations import run
def connect_and_wait():
#ssh.config.socket.setdefaulttimeout(5)
socket.setdefaulttimeout(5)
print('SSTART')
run('echo START')
run('sleep 10')
run('echo END')
print('EEND')
The script above prints everything without any error/exception.
Python 2.6.5, Fabric 1.4.2.
socket.setdefaulttimeout() does not work.
ssh.config.socket.setdefaulttimeout() does not work.
fabric.api.env['timeout'] is for connecting phase only I suppose.
Fabric uses "lazy" connections to remote hosts and can automatically reconnect when executing task on a host and connection is lost. Seems there is no way to explicitly drop idling connections, but you can close all connections and let fabric reconnect to "active" hosts. fabric.network.disconnect_all() do the trick.