Showing posts with label SSH. Show all posts
Showing posts with label SSH. Show all posts

Thursday, July 4, 2019

Access Remote Webcam (Take Picture and Live Stream), Access VNC Through SSH

Take picture on remote and display locally

ssh cloud_raspi 'fswebcam tapeiga.png && cat tapeiga.png' | display

Take screenshot on remote and display locally

ssh cloud_raspi 'DISPLAY=:0 scrot tapeiga2.png && cat tapeiga2.png' | display

Live video recording on remote and live display locally

ssh cloud_raspi ffmpeg -an -f video4linux2 -s 640x480 -i /dev/video0 -r 10 -b:v 500k -f matroska - | mplayer - -idle -demuxer matroska

Turn on TV connected on HDMI, on remote

ssh cloud_raspi 'vcgencmd display_power 1'

Turn off TV connected on HDMI, on remote

ssh cloud_raspi 'vcgencmd display_power 0'

Live Record Video Locally and Live Display on Remote TV
ffmpeg -an -f video4linux2 -s 640x480 -i /dev/video0 -r 10 -b:v 500k -f matroska - | ssh cloud_raspi 'DISPLAY=:0 mplayer - -idle -demuxer matroska'

Live Record Audio Remotelly and play Locally
ssh cloud_raspi "arecord -f cd -D plughw:1 | ffmpeg -ac 1 -i - -f ogg - " | mplayer - -idle -demuxer ogg
Live Record Audio Locally and Play on Remote
arecord -f cd -D plughw:1 | ffmpeg -ac 1 -i - -f ogg - | ssh cloud_raspi 'mplayer - -idle -demuxer ogg'
or
arecord -f cd | ssh cloud_raspi 'aplay'
or
arecord -f S16_LE -r 3600 | ssh cloud_raspi 'aplay'

Connect on VNC via cloud

On remote machine start VNC Server
and start a tunnel
ssh -R 6900:localhost:5900 user@mycloudserver.com

On local machine start a tunnel
ssh -L 5900:localhost:6900 user@mycloudserver.com
and connect vnc client to localhost
vncviewer localhost




Tuesday, June 25, 2019

ssh multiple hops / SSH Config


ssh -tt user_b@HOSTB ssh user_c@HOSTC -p 4567

ssh -J user_b@HOSTB,user_c@HOSTC user_d@HOSTD



Exemplos de ~/.ssh/config

------------------------------------------------------------------------------------------------------- user_a@HOSTA -> user_b@HOSTB:22 -> user_c@HOSTC:4567

Host *
   ControlPersist 18000
   ControlMaster auto
   TCPKeepAlive yes
   ServerAliveInterval 30


Host c_jump1
  User user_c
  Hostname HOSTC
  Port 4567
  ControlPath /tmp/ssjump1
  ProxyCommand ssh -W %h:%p user_b@HOSTB

Host c_jump2
  User user_c
  Hostname HOSTC
  Port 4567
  ControlPath /tmp/ssjump2
  ProxyCommand ssh user_b@HOSTB exec nc %h %p

------------------------------------------------------------------------------
user_a@HOSTA -> user_b@HOSTB:22 -> user_c@HOSTC:4567 -> user_d@HOSTD:7890

Host c_jump3
  Hostname HOSTD
  User user_d
  Port 7890
  ControlPath /tmp/ssjump3
  ProxyJump user_b@HOSTB:22,user_c@HOSTC:4567


-----------------------------------------------------------------------------
# man 5 ssh_config

https://www.systutorials.com/docs/linux/man/5-ssh_config/
http://www.openssh.com/txt/release-5.4

Transfer file through ssh connection using cat pipe

cat z.cpp | ssh user@hostname 'cat > /remote_folder/copy_of_z.cpp'

ssh user@hostname 'cat /remote_folder/copy_of_z.cpp' > z.cpp

Friday, January 25, 2019

Auto Login with Python + SSH + Expect

Python and Expect

#!/usr/bin/python                                                                                                                     
import argparse
from ConfigParser import ConfigParser
import pexpect

def main(args):
    url = args.url
    user, host = url.split('@', 1)

    cfg_file = '/home/user/bala_python.passwords'
    cfg = ConfigParser()
    cfg.read(cfg_file)
    passwd = cfg.get(user, host)

    child = pexpect.spawn('ssh {0}'.format(url))
    child.expect('password:')
    child.sendline(passwd)
    child.interact()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Run ssh through pexpect')
    parser.add_argument('url')
    args = parser.parse_args()
    main(args)

....
bala_python.passwords
[user1]
host1 = password1
host2 = password2

[user2]
host1 = password1
host2 = password2

Wednesday, February 28, 2018

Expect to login in ssh server through balabit

#!/usr/bin/expect -f

trap {
   set XZ [stty rows   ]
   set YZ [stty columns]
   stty rows $XZ columns $YZ < $spawn_out(slave,name)
} WINCH


proc getpass pwprompt {
       set oldmode [stty -echo -raw]
       send_user "\n     $pwprompt"
       set timeout -1
       expect_user -re "(.*)\n"
       send_user "\n"
       eval stty $oldmode
       return $expect_out(1,string)
}

set host [lrange $argv 0 0]

#Save Last Path ########
set last_path_file "/tmp/.save_bala_ssh_$host.txt"
if {[file exists $last_path_file]} {
       set f [open "/tmp/.save_bala_ssh_$host.txt"]
       set lp [split [read $f] "\n"]
       set last_path [lindex $lp 1]
       send_user "Last Path for host $host: $last_path\n"
       close $f
}
########################

#set user [lrange $argv 1 1]
set user "usuario_balabit"
set path [lrange $argv 1 1]
#set pass [getpass "Password: "]
set pass "senha_balabit"
set timeout -1
#spawn -noecho bash;
#send "ssh -A $host\r"
spawn ssh -t $host
set passwords { "senha1" "senha2" "senha3" }
set try 0
##
set timeout 2
expect {
       "Gateway username: " {
               send -- "$user\r"
               exp_continue
       }

       "Gateway password: " {
               send -- "$pass\r"
               exp_continue
       }

       "password:" {
               if { $try >= [llength $passwords] } {
                       send_error ">>> wrong passwords\n"
                               exit 1
               }
               send -- "[lindex $passwords $try]\r"
               incr try
               set timeout 3
               exp_continue
       }

       "denied" {
               set timeout 5
               exp_continue
       }

       timeout {
               #interact
               send_user "\nOK Cool! Finally Connected\n"
               if { $path != "" } {
                       if { $path != "-l" } {
                               send  -- "\nclear\ncd $path\n"
                       } else {
                               send  -- "\nclear\ncd $last_path\n"
                       }
               }
               #interact
               set CTRLZ \032
               interact {
                       -reset $CTRLZ {exec kill -STOP [pid]}
                       #\003   exit
                       #mostra_data {
                       #       send_user "The date is [exec date]."
                       #}
                       #foo {
                       #       send_user "bar"
                       #}
                       #\001   {send_user "you typed a control-A\n";
                       #       send "\001"
                       #}
                       #\002   {send_user "you typed a control-B\n";
                       #       send "\002"
                       #}
                       ç {
                               send "pwd\r"
                               expect "/*\n"
                               puts [open $last_path_file w] $expect_out(buffer)
                       }
               }
       }
}

Wednesday, September 6, 2017

Send mail on ssh login and logout

Login
/etc/ssh/sshrc

Logout
/etc/pam.d/sshd

session optional pam_exec.so quiet /etc/pam_session.sh

/etc/pam_session.sh

#!/bin/sh
if [ "$PAM_TYPE" = "close_session" ]; then
something
fi

https://unix.stackexchange.com/questions/136548/force-command-to-be-run-on-logout-or-disconnect

Wednesday, April 5, 2017

SSH Tunnel with SSHFS to bypass balabit restriction

Tunnel ssh/balabit

Client

1. mount the remote filesystem with sshfs

$ sshfs sshremote_server:/tmp /tmp/remote_dir

2. mock your webserver with netcat and redirect request to the file /request
and response to the  file response

$ while true; do
    nc -l 8080  < /tmp/remote_dir/response  | cat > /tmp/pastaremota/request;
done

3. Unmount the filesystem
fusermount -u /tmp/remote_dir

Server behind balabit

Wait for input in file request with tail and redirect to the real webserver using netcat

$ while true; do
    tail -f /tmp/request | nc localhost 10010 > /tmp/response;
done

SSH File System (Mount a remote folder using ssh)

To mount the remote directory /tmp/remote_test to the local /tmp/local_test

$ sshfs servidorssh:/tmp/remote_test /tmp/local_test/

Now you can use you favorite graphical file manager such as dolphin to transfer files, or you can even edit a remote file as it was a local file
for example

$ dolphin /tmp/local_test

$ kwrite /tmp/local_test/remotefile

To unmount
$ fusermount -u /tmp/local_test

Sunday, May 22, 2016

Make your home PC accessible from a cloud computer using ssh reverse

Inspired by MR. Robot Raspberry attack


First of all, you need a server with ssh access in the cloud, you can purchase a free one from amazon aws, let's call it mycloud

I want access my home pc (myhome) from my job pc (myjob).

First let's make myhome always connect to mycloud everytime it is connected to the internet. Since it's debian based linux, I write a script that I will call  connect2mycloud and save it into /etc/network/if-up.d/ directory

inside /etc/network/init.d/connect2mycloud type the following and save it

ssh -R 12345:localhost:22 clouduser@mycloud
#su -c "autossh -f -N -R 12345:localhost:22 clouduser@mycloud -oStrictHostKeyChecking=no" myhomeuser

For RedHat based create a file called 15-connect2mycloud in the directory /etc/NetworkManager/dispatcher.d/
and inside /etc/NetworkManager/dispatcher.d/15-connect2mycloud type the following and save it

if [ "$2" = "up" ]; then     
   ssh -R 12345:localhost:22 clouduser@mycloud 
   #su -c "autossh -f -N -R 12345:localhost:22 clouduser@mycloud -oStrictHostKeyChecking=no" myhomeuser

fi

Doing this every time myhome is connected to the internet it will create a ssh reverse connection from mycloud. So once I am logged into mycloud I can just do ssh -p 12345 localhost, then I will connect to myhome

Ok, now I'm at myjob pc, and want to connect to myhome directly with only one command

To achieve this you must create an entry in your ~/.ssh/config file with a proxy command
so in myjob  I add the following entry in ~/.ssh/config file like this

Host myhome
   User myuser
     ControlMaster auto
ControlPath /tmp/ssh-%r@%h:%p 
ProxyCommand ssh myuser@mycloud nc localhost 12345 2> /dev/null

Now to connect to myhome, I just run
# ssh myhome    
It will ask me mycloud and after myhome password in sequence, or nothing if I use public key

If you want to execute screen on remote host you need to  use -tt (alocate tty) like this
# ssh -tt myhome screen -dR

If you don't want to edit ssh config file use the command
# ssh -tt myuser@mycloud 'ssh  -tt localhost -p 12345'
you can also call screen reattach
# ssh -tt myuser@mycloud 'ssh  -tt localhost -p 12345'  screen -dR

Tuesday, March 8, 2016

Reverse SSH


In /etc/ssh/sshd for Computer B set:

AllowTcpForwarding yes
TCPKeepAlive yes

From Computer A:
$ ssh -R 2222:localhost:22 ip.of.computer.b

From Computer B:
$ ssh localhost -p 2222

Tuesday, December 29, 2015

HTTP Proxy with ssh

ssh to your server
$ ssh -D 5222 -C user@yoursshservertobeusedasproxy

No firefox coloque em SOCKS  localhost porta 5222 e marque a opção DNS Remoto e a opção SOCKS5




How to setup SSH Proxy on Android using firefox and Connectbot
http://www.devineloper.com/2013/08/28/setup-socks-proxy-android-without-root/

Monday, December 14, 2015

Expect to automate login in ssh or balabit

#!/usr/bin/expect -f

set force_conservative 0  ;# set to 1 to force conservative mode even if
              ;# script wasn't run conservatively originally
if {$force_conservative} {
    set send_slow {1 .1}
    proc send {ignore arg} {
        sleep .1
        exp_send -s -- $arg
    }
}

set timeout -1
spawn ssh -l user@target29  balabit_address
match_max 100000
expect -exact "Gateway username: "
send -- "seu_usuario_balabit_aqui\r"
expect -exact "seu_usuario_balabit_aqui\r
Gateway password: "
send -- "seu_password_balabit_aqui\r"
expect -exact "password: "
send -- "senha_do_maquina_target\r"
interact


Criar arquivo automaticamente conforme vai se digitando
autoexpect -f  arquivo_expect  ssh -l user@target29 balabit_address
Usar arquivo gerado
expect -f arquivo_expect



Tuesday, December 8, 2015

SSH Tips

~/.ssh/config

Host *
    ControlMaster auto
    ControlPath /tmp/ssh-%r@%h:%p
    ControlPersist 600
    ServerAliveInterval 60

Host myssh
    User thiago
    Hostname server.ssh.com


$ ssh  myssh
type password
open a new terminal
$ ssh myssh
no password will be required since it will use the same connection


SFTP

Sending file

$ echo "put example.txt /tmp/" | sftp myssh
$ sftp myssh <<< "put example.txt /tmp/"

Geting files from

$ echo "get /remotefolder/*  /tmp/" | sftp myssh
$ sftp myssh <<< "get /remotefolder/*  /tmp/"

Cat & ssh

Send file

$ cat example.txt | ssh myssh 'cat > /tmp/example.txt'

Receive file

$ ssh myssh 'cat /tmp/example.txt' | cat > /tmp/example.txt


ssh via balabit

$ ssh -l usario@hostdestino hostbalabit

sftp via balabit

$ sftp -o User=usuario@hostdestino hostbalabit



Sunday, June 12, 2011

Acesso remoto via Eclipse + tunnelamento ssh

Fazendo um site usando JSP e Servlets Java, com servidor hospedado em uma maquina da faculdade, eis que da minha necessidade (editar codigo java remotamente, e infelizmente eclipse é melhor que emacs quando se trata de java) descobri essa funcionalidade do Eclipse.
Edição remota de arquivos com o plugin
Remote System Explorer.
Update Site: http://download.eclipse.org/tm/updates/3.2/

como a maquina servidora só é acessivel pela rede interna e todos os alunos possuem acesso ssh a rede, aproveito aqui para deixar também a dica de tunelamento ssh.

Para acessar meu site hospedado na maquina da rede interna

(ssh/putty) -L 2800:maquinainterna:8080 minhaconta@ssh.dominiodafacul.com.br
no browser localhost:2800

para editar meus site pelo eclipse

(ssh/putty) -L 2809:maquinainterna:22 minhaconta@ssh.dominiodafacul.com.br

no eclipse host: localhost, port: 2809

Wednesday, April 7, 2010

Emacs + Cscope

To Install in Debian/Ubuntu

sudo apt-get install cscope

write this 2 lines in you .emacs
...
(load-file "/usr/share/emacs/site-lisp/xcscope.el")
(require 'xcscope)
...

Then, if you have code in ~/mycode, cd to that directory and run
Code:
myusernam@mycomputer:~/mycode$ cscope-indexer -r

run emacs

myusernam@mycomputer:~/mycode$ emacs main.c

put the cursor on the word you want to search and

alt+x (and one of the the options bellow)
cscope-find-called-functions
cscope-find-egrep-pattern
cscope-find-files-including-file
cscope-find-functions-calling-this-function
cscope-find-global-definition
cscope-find-global-definition-no-prompting
cscope-find-this-file
cscope-find-this-symbol
cscope-find-this-text-string

Wednesday, March 24, 2010

Convert ssh key to putty format

sudo apt-get install putty-tools
puttygen /path/to/ssh-gen-privatekeyfile -O private -o /path/to/putty-formatted-privatekeyfile

Blog Archive