RLY-8 POE relay using json - json

just got the DFrobot relay and trying to communicate with it using json commands
pdf is here
any help please how to send an on/off command from terminal?

That is pretty easy, just open a telnet to the device, an example:
telnet 192.168.1.10 2000
and copy paste one of the JSON commands from their pdf document, like:
{"relay1":"on","relay2":"on","relay3":"off","relay4":"off","relay5":"off", "relay6":"off","relay7":"off","relay8":"off"}
and hit enter. In case if you want more than telnet commands you can check this Github project.

please check : https://github.com/Dzduino/DFRobot-RLY-8-Web-Control/blob/master/index.php
You can use PHP Socket like bellow in an html or PHP page, please note that you have to use some local php server (Ex: XAMPP) to test it:
<?php
$addr = "192.168.1.10"; // RLY-8 Default Adress
$port = 2000; // RLY-8 Default port
$timeout = 30; // Connection Time out in Sec
if (isset($_POST["cmd"])){ // check if a submit was done, otherwise the communicatino will start after page loading
$cmd = $_POST["cmd"] ; // Capture the input Command
$fp = fsockopen ($addr, $port, $errno, $errstr, $timeout ); // initiate a socket connection
if (!$fp) {
echo "($errno) $errstr\n"; // return the error if no connection was established
} else {
fwrite ($fp, $cmd); // Send the command to the connected device
echo fread($fp, 128); // Echo the return string from the device
fclose ($fp); // close the connection
}
}
?>

Related

Trying to automate Tor to do something on a site and change identity each time. Need some guidance

I really need some help with automating Tor to do something on a site (in this case, check something on a poll) and then restart Tor with a new identity. I have never done anything remotely close to this. I only know HTML, CSS and JS fairly well.
Now, to sum up, I want to make a loop that repeatedly accesses a site on Tor, checks something on that site and then restarts Tor with a new identity.
If anyone could give me some guidance and tell me what I can use, it would be much appreciated. I have the time and patience to learn, so anything works really.
Here are examples using PHP and Python 3 to accomplish what you want. They're simple starting points for making requests over Tor and changing your identity on demand.
The PHP example uses TorUtils to communicate with the controller and wrap cURL through Tor.
The Python example uses stem to communicate with the controller and Requests for sending requests over Tor's SOCKS proxy.
The examples assume you have Tor working already and the SocksPort set to 9050, and the ControlPort set to 9051 with cookie authentication working, or a controller password of password.
PHP
Set Up
Install Composer to install the TorUtils package (you can also download the zipball and extract)
Once composer is working, run composer require dapphp/torutils from your project directory to download and install dependencies
Code
<?php
use Dapphp\TorUtils\ControlClient;
use Dapphp\TorUtils\TorCurlWrapper;
require_once 'vendor/autoload.php'; // composer autoloader
// include TorUtils/src/ControlClient.php and TorUtils/src/TorCurlWrapper.php if using without composer
$controller = new ControlClient; // get a new controller object
try {
$controller->connect('127.0.0.1', 9051); // connect to Tor controller on localhost:9051
$controller->authenticate('password'); // attempt to authenticate using "password" as password
} catch (\Exception $ex) {
die("Failed to open connection to Tor controller. Reason: " . $ex->getMessage() . "\n");
}
// issue 10 requests, changing identity after each request
for ($i = 0; $i < 10; ++$i) {
try {
$curl = new TorCurlWrapper('127.0.0.1', 9050); // connect to Tor SOCKS proxy on localhost:9050
$curl->httpGet('https://drew-phillips.com/ip-info/'); // issue request
$body = strip_tags($curl->getResponseBody());
if (preg_match('/Using Tor:\s*Yes/i', $body)) {
echo "You appear to be using Tor successfully. ";
} else {
echo "Proxy worked but this Tor IP is not known. ";
}
if (preg_match('/IP Address:\s*(\d+\.\d+\.\d+\.\d+)/i', $body, $ip)) {
echo "Source IP = {$ip[1]}\n";
} else {
echo "Couldn't determine IP!\n";
}
} catch (\Exception $ex) {
echo "HTTP request failed! " . $ex->getMessage() . "\n";
}
// TODO: issue more requests as needed here
echo "\n";
sleep(10);
try {
// send signal to controller to request new identity (IP)
$controller->signal(ControlClient::SIGNAL_NEWNYM);
} catch (\Exception $ex) {
echo "Failed to issue NEWNYM signal: " . $ex->getMessage() . "\n";
}
}
Python 3
Set Up
This example uses Python 3 and assumes you have the Python interpreter up and running and have the following packages installed: requests, requests[socks], socks, urllib3, stem.
On Debian/Ubuntu: sudo -H pip3 install requests requests[socks] socks urllib3 stem
Code
#!/usr/bin/env python3
import requests
from stem.control import Controller, Signal
import time
import sys
import re
# specify Tor's SOCKS proxy for http and https requests
proxies = {
'http': 'socks5h://127.0.0.1:9050',
'https': 'socks5h://127.0.0.1:9050',
}
try:
controller = Controller.from_port(9051) # try to connect to controller at localhost:9051
except stem.SocketError as exc:
print("Unable to connect to tor on port 9051: %s" % exc)
sys.exit(1)
try:
controller.authenticate('password') # try to authenticate with password "password"
except stem.connection.PasswordAuthFailed:
print("Unable to authenticate, password is incorrect")
sys.exit(1)
# issue 10 requests, changing identity after each request
for i in range(1,10):
# issue request, passing proxies to request
r = requests.get('https://drew-phillips.com/ip-info/', proxies=proxies)
#print(r.text)
m = re.search('<dt>Using Tor:</dt><dd><span[^>]*>Yes', r.text)
if m:
print("You appear to be using Tor successfully. ", end="")
else:
print("Proxy worked but this Tor IP is not known. ", end="")
m = re.search('<dt>IP Address:</dt><dd>(\d+\.\d+\.\d+\.\d+)</dd>', r.text)
if m:
print("Source IP = %s" % m.groups(1))
else:
print("Failed to scrape IP from page")
try:
# send signal to controller to request new identity (IP)
controller.signal(Signal.NEWNYM)
except Exception as ex:
print("NEWNYM failed: %s" % ex)
time.sleep(10)

Grant Google Access to SMTP on cPanel/WHM Centos Server without advertising SMTP Auth?

A non-stop wave of distributed smtp auth attacks on my server prompted me to ban non specified IPs from connecting to smtp on my server and sending mail though it. Very effective. (instructions: http://sysadmintips.in/advanced/csf/exim)
However I now cannot use Google Mail (Gmail) to 'Send Mail As' for new accounts without either enabling two-factor authentication (which is a pain as I'm setting this up remotely for my clients) or switching smtp auth back on on my server.
My other option would be to white-list Google Mail's IP addresses.
Google searching discovered this way to retrieve the current Google IP ranges using something along these lines (which I've copied from this page: https://support.google.com/a/answer/60764?hl=en):
nslookup -q=TXT _spf.google.com 8.8.8.8
This returns a list of the domains included in Google's SPF record, such as:
_netblocks.google.com, _netblocks2.google.com, _netblocks3.google.com
Now look up the DNS records associated with those domains, one at a time, like so:
nslookup -q=TXT _netblocks.google.com 8.8.8.8
nslookup -q=TXT _netblocks2.google.com 8.8.8.8
nslookup -q=TXT _netblocks3.google.com 8.8.8.8
The results of these commands contain the current range of addresses.
Can I use the output of these to generate useful content for /etc/csf/csf.smtpauth ?
I can code something to do this in PHP and run it as a cron task as root, but what format is acceptable? Does csf.smtpauth accept IP range declarations? Does it cope OK with IPV6 IPs?
After any change I'll also need to force a restart of csf and lfd automatically so the new IPs are in use. Is that possible from PHP running as root?
Thanks!
Solved.
I've coded up the following PHP which queries Google's SPF records and then, only if required, will replace the existing SMTP Auth block with a new one. It then creates a file which is used as a flag for a bash script to re-start the firewall.
Note that /etc/csf/csf.smtpauth accepts IPV4 and IPV6 addresses and CIDR address ranges.
// Grab current Google SPF IPs...
$dns = dns_get_record('_spf.google.com', DNS_TXT);
if (!$dns)
{
echo "FAILED TO RETRIEVE DNS RECORD<br />\n";
exit;
}
// The variable in which to store the results
$ranges = array();
// Of interest in particular to us is...
$val = $dns[0]['txt'];
preg_match_all("/include:[^\s]+\s/", $val, $matches);
if (sizeof($matches[0]) <= 0)
{
echo "BAD DATA RECEIVED OR FAILED TO DECODE DATA<br />\n";
exit;
}
foreach ($matches[0] as $match)
{
$match = trim($match);
$domain = trim(preg_replace("/include\:/", "", $match));
// Now do it all again for this domain to get the IP range
$dns = dns_get_record($domain, DNS_TXT);
if (!$dns)
{
echo "DNS LOOKUP FAILURE AT PASS 2<br />\n";
exit;
}
$val = $dns[0]['txt'];
preg_match_all("/ip\d:[^\s]+\s/", $val, $ips);
if (sizeof($ips[0])<=0)
{
// At time of writing this is entirely possible as _netblocks3.google.com
// currently holds NO IP ranges
}
else
{
foreach ($ips[0] as $ip)
{
$ip = trim($ip);
if ($ip <> '')
{
$ip = preg_replace("/ip\d\:/", "", $ip);
$ranges[] = $ip;
}
}
}
}
// To be here means we made it without a major problem. Form the new IP range for
// the smtp auth file (/etc/csf/csf.smtpauth) and compare with the existing. Update only if there has
// been a change. Also update only if there are at least N ranges found.
// When I wrote this there were 11 IPV4 ranges and 6 IPV6 ranges so setting
// low limit to 10
$limit = 10;
$filename = '/etc/csf/csf.smtpauth';
if (sizeof($ranges) < $limit)
{
echo "NOT UPDATING RANGES, TOO FEW DISCOVERED, PROBLEM?";
exit;
}
$filerange = "# GOOGLE SPF RESULTS START\n";
$filerange .= join("\n", $ranges);
$filerange .= "\n# GOOGLE SPF RESULTS END";
// Read in existing conf file
$econf = file_get_contents($filename);
if (sizeof($econf)<=0)
{
echo "FAILED TO READ $filename<br />\n";
exit;
}
// Extract the block
if (!preg_match("/\# GOOGLE SPF RESULTS START.+\# GOOGLE SPF RESULTS END/s", $econf, $matches))
{
echo "FAILED TO FIND EXISTING BLOCK. CORRUPT AUTH FILE?<br />\n";
exit;
}
if ($filerange == $matches[0])
{
// IT'S THE SAME DO NOT UPDATE IT!;
exit;
}
// Replace the block entirely
$econf = preg_replace("/\# GOOGLE SPF RESULTS START.+\# GOOGLE SPF RESULTS END/s", $filerange, $econf);
// Write out the new file contents
file_put_contents($filename, $econf);
// Trigger a CSF/LFD restart by creating trigger file.
touch("restartcsflfd");
Then create a CRON task to run this shell script shortly after and each time the above is run:
#!/bin/bash
if [ -f /path-to-file/restartcsflfd ];
then
csf -r
/etc/init.d/lfd restart
rm -f restartcsflfd
echo "RE-STARTED CSF and LFD"
fi

Placing SQUID ACL's in MySQL DB - is it possible?

The main question is whether it is possible to create squid acl to receive credentials from the mysql database?
Description of the situation.
Device PI - Raspberry PI
Device B - Computer
Server
PI connects to the server, knowing its static IP, this opens the port while running a reverse shell, so pinging the server on a given IP address and port get access to PI. Device B wants to communicate with the PI, and does not know its IP so it tryies to ping the server from which receives information on which port is PI.
This operation is performed on the squid server - for the user from the database (I did it from tutorials - squid auth over mysql DB) server gets the information if user can be logged on the proxy server.
I wish I could also generate squid ACL on DB, so I would know on what ports to specific PI users can get.
So in the ACL would be placed information on which local port of server user can be authenticate (there will run a reverse shell so it automatically connect to PI)
Is possible using external_acl or rewrite_program.
For programtion use C, Perl, PHP, ShellScript.
You need only return ERR for negation or OK for allow the access.
On external_acl you can pass to program any parrametres, url, port destination, port source, ip source, domain destionation, user.
basic example, allow access the "google"
#!/usr/bin/php -q
<?php
include "mysql.php";
include "funcoes.php";
$temp = array();
stream_set_timeout(STDIN, 86400);
if (!defined(STDIN)) {
define("STDIN", fopen("php://stdin", "r"));
}
while (!feof(STDIN)) {
$input = trim(fgets(STDIN));
$found = 0;
$login = 0;
$temp = split(' ', $input);
$output = $temp[0] . "\n";
$url_output = $output;
$url_output_debug = $temp[0];
$pos = strpos($url_output, 'google');
if ($pos !== false) {
$output = "OK \n";
$found = 1;
} else {
$output = "ERR \n";
}
fwrite(STDOUT, $output);
}
?>

perl tcp socket server to mysql

i have to create a little perl script which is creating an tcp socket and put the input from this socket into an mysql table.
Background: I get Call Data Records from a Siemens Hipath phone system via this TCP Socket.
I have to write the data, which is CSV in an DB for future use.
The format i get is following: 13.05.14;15:01:14;3;10;00:26;00:00:45;0123456789;;1;
Im new to perl, an have a few "noob" questions :)
1: How is it possible to run that script in background (as deamon) ?
2: The Script is only handling the last line of an deliverd csv line. If there are two lines, it ignores the first line. How can i fix that ?
3: Today i got this output from my script: DBD::mysql::st execute failed: MySQL server has gone away at ./hipath-CDR-Server.pl line 41. What happend there?
Can anyone help me with that maybe easy questions.
This is what i got till now:
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
use IO::Socket::INET;
my $dbh = DBI->connect('DBI:mysql:database=hipathCDR;host=localhost','***','***',{ RaiseError => 1, AutoCommit => 1 }, );
my $sql = 'INSERT INTO calls (Datum,Zeit,Leitung,Teilnehmer,Rufzeit,Gespraechszeit,RufNr,Gebuehr,Typ) VALUES (?,?,?,?,?,?,?,?,?)';
my $sth = $dbh->prepare($sql);
# auto-flush on socket
$| = 1;
# creating a listening socket
my $socket = new IO::Socket::INET (
LocalHost => '0.0.0.0',
LocalPort => '4444',
Proto => 'tcp',
Listen => 5,
Reuse => 1
);
die "cannot create socket $!\n" unless $socket;
while(1)
{
# waiting for a new client connection
my $client_socket = $socket->accept();
# get information about a newly connected client
my $client_address = $client_socket->peerhost();
my $client_port = $client_socket->peerport();
# read up to 1024 characters from the connected client
my $data = "";
$client_socket->recv($data, 1024);
chomp ($data);
my #values = split(';', $data);
print "Array: #values\n";
$sth->execute(#values);
# write response data to the connected client
$data = "ok";
$client_socket->send($data);
# notify client that response has been sent
shutdown($client_socket, 1);
}
$socket->close();
You have more than one question, I am going to answer the second: Here is howto get all data.
my $data = "";
while ($client_socket->recv($data, 1024)){
$data .= $_;
}
It would more safer to parse the incoming CSV like data by Text::CSV.
Answer to question three:
Most probably your mysql was unavailable that time.
Answer to question one:
nohup ./script.pl &
Okay, I am just kidding: How can I run a Perl script as a system daemon in linux?
use Proc::Daemon;
Proc::Daemon::Init;
my $continue = 1;
$SIG{TERM} = sub { $continue = 0 };
...
while($continue)
{
...
}

Script to change FTP password

I have the following script to update one of my FTP passwords every 15 days through a cronjob and e-mail the appropriate people after the attempt has been made. It randomly will fail and so I will run it again manually and it will work. I can't seem to find where it's going wrong.
The script is connecting to a local mysql database grabbing the login and password for an account and then changing that password on FTP. Everything is successful up until the changing the password part. Again it's random, sometimes it works, sometime it doesn't.
Thanks!
#!/usr/bin/perl -w
#
use DBI;
use Net::FTP;
our $dbh = DBI->connect('DBI:mysql:database:127.0.0.1','user','password') or die "Aargh $!\n";
$transquery=q{SELECT dest_login,dest_password FROM list where id=123};
$sth=$dbh->prepare($transquery);
$sth->execute();
while($co=$sth->fetchrow_hashref){
$login=$co->{'dest_login'};
$pass=$co->{'dest_password'};
}
$changeresult='FAIL';
$actionlog='';
$newstring='';
$upperchars='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$lowerchars='abcdefghijklmnopqrstuvwxyz';
$allowedchars='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789##$';
$l=length($upperchars);
$newstring.=substr($upperchars,int(rand($l)),1);
$newstring.=substr($lowerchars,int(rand($l)),1);
$l=length($allowedchars);
for ($i=0;$i<6;$i++){
$newstring.=substr($allowedchars,int(rand($l)),1);
}
print "$newstring\n";
$actionlog .= "Setting Password for $login from $pass to $newstring\n";
$username=
eval{
$ftp=Net::FTP->new('x.x.x.x',Timeout=>480,Debug=>1) or die "Error connecting FTP $!\n";
$changepassword="$pass/$newstring/$newstring";
$ftp->login($login,$changepassword) or die "Error changing password $!\n";
#If we are here, time to update the password
$changeresult='SUCCESS';
$actionlog .= "Password successfully updated\n";
$transquery=q{UPDATE list set dest_password=(?) where id=123};
$sth=$dbh->prepare($transquery);
$sth->execute($newstring);
};
if ($#) {
$actionlog = $actionlog . "$#\n";
};
if($actionlog ne ""){
#print $actionlog;
#my $send_to = "To: someone\#example.com\n";
my $send_to = "To: databaseusers\#example.com\n";
my $sendmail = "/usr/sbin/sendmail -t";
open(SENDMAIL, "|$sendmail") or die "Cannot open $sendmail: $!";
print SENDMAIL "Reply-to: databasepassword\#example.com\n";
print SENDMAIL "Subject: Password Change Information [$changeresult]\n";
print SENDMAIL $send_to;
print SENDMAIL "Content-type: text/plain\n\n";
print SENDMAIL $send_to;
print SENDMAIL "Content-type: text/plain\n\n";
print SENDMAIL $actionlog;
close(SENDMAIL);
$actionlog='';
}
else{
#print "Nothing done this session\n";
USUW might tell you something. ( use strict; use warnings; )
Does anything print?
You don't do much error checking in the DBI part at the beginning, perhaps you're getting a connect error. AIX boxes used to have this problem of getting a client port that the system was unsure about whether or not it was in use. When that happened, it would just fail to connect to the database.
I finally fixed that problem for our scripts by examining the $OS_ERROR ( aka $! ) for that particular code ( Errno::EADDRINUSE ) and then waiting and retrying, with an exponential falloff ( wait 2 seconds, then 4, then 8 ... ).
If your script "dies for some reason" then it's important the script can tell you that reason. I would investigate the topic of error reporting in the various modules you are using.
For example Net::FTP allows you to pass a Debug => 1 switch, and then you'll see the whole conversation.
And I know that there is a whole lot more with DBI where you can get error reporting.