Показаны сообщения с ярлыком net. Показать все сообщения
Показаны сообщения с ярлыком net. Показать все сообщения

вторник, 25 августа 2015 г.

rsync speed


-e "ssh Ciphers=arcfour"
"ssh Compression=no"

суббота, 23 июля 2011 г.

kvm network

Перепост. Источник: http://forum.vingrad.ru/index.php?showtopic=248685&view=findpost&p=180624

# убираем ip адрес у интерфейса eth0
/sbin/ip addr flush eth0
# "Опускаем" eth0
/sbin/ip link set eth0 down
# Переименовываем reth0 (тут нам нужно знать MAC-адрес инрефейса)
/sbin/nameif reth0 00:11:22:33:44:55
# "Подымаем" reth0 (eth0 в девичестве)
/sbin/ip link set reth0 up
# Создаём мост с именем eth0
/usr/sbin/brctl addbr eth0
# "Подымаем" eth0
/sbin/ip link set eth0 up
# Добавляем к мосту интерфейс reth0
/usr/sbin/brctl addif eth0 reth0
# Назначаем IP для eth0, тут надо отметить, что в случае получения адреса по DHCP нужно будет
# убить dhcpcd (/usr/sbin/dhcpcd -k) перед тем как освободить адрес eth0, а потом снова запустить (/sbin/dhcpcd -n)
ifconfig eth0 192.168.0.3
# Так как DHCP я не использую, а default route погибает вместе с опусканием eth0, его нужно восстановить
route add -net default gw 192.168.0.1
# Создаём tap интерфейс
tunctl -u _имя_пользователя_из_под_которого_пускается_qemu_ -t qeth0
# "Подымаем" qeth0
# добавляем tap-интерфейс в мост
/usr/sbin/brctl addif eth0 qeth0
# Т.к. моя машина смотрит в несколько сетей, дефолтовое действие для цепочки FORWARD у меня DROP.
# Нужно добавить правило, которое выглядит слегка не логично :)
# Если у вас не разрешён форвардинг, надо его разрешить (echo 1 > /proc/sys/net/ipv4/ip_forward)
/sbin/iptables -A FORWARD -i eth0 -o eth0 -j ACCEPT

Теперь из под пользователя запускаем qemu (или kvm, что конечно лучше ), опции по вкусу Без подсветки
1:
kvm -m 128 -hda gw.img -cdrom /mnt/frenzy-1.1-std-RU.iso -net nic,vlan=0,macaddr=52:54:00:12:34:57 -net tap,vlan=0,ifname=qeth0,script=no -monitor stdio -vnc localhost:0




Всё работает как часы, qemu/kvm даже получает адрес по DHCP

Несколько замечаний:

Зачем нужно переименовывать eth0? У меня eth0 не однократно фигурирует в правилах iptables, если у Вас нет такой проблемы можно дать мосту имя по умолчанию (br0) и не усложнять процедуру.

Если Вы хотите запустить несколько виртуальных машин, то вам понадобится отдельный интерфейс для каждой машины, либо (что ИМХО более разумный выход) воспользоваться программой vde_switch, но это уже другая история

Если Вы используете несколько виртуальных машин, не забудьте назначить им разные MAC-адреса (я на эти грабли умудрился наступить )

Ну что ж, вроде я ничего не забыл. Желаю удачи

четверг, 30 июня 2011 г.

External VNC viewer for KVM

#!/bin/bash
ip addr show eth0 | grep inet
echo "VDS: $1 Password $2 Port: 5$1  "
Wait connection...
nc -l -p 5$1 -c "qm vncproxy $1 $2"


или

#remote
socat TCP-LISTEN:5500 EXEC:'ssh root@tee.schottelius.org "socat STDIO UNIX-CONNECT:/home/services/vms/vnc-socket"'

#local
xtightvncviewer -encodings "copyrect tight hextile zlib corre rre raw" localhost:5500

или через программку из проекта Proxmox
vncterm [VNCOPTS] [-c command [ARGS]]
#example:
vncterm -c vzctl enter VMID
vncterm -rfbport 5900 -passwdfile FILE -timeout 20 -c vzctl enter 104

понедельник, 23 мая 2011 г.

Port forwarding on Linux without iptables?

socat TCP4-LISTEN:80,fork TCP4:www.yourdomain.org:8080

http://serverfault.com/questions/252150/port-forwarding-on-linux-without-iptables

понедельник, 16 мая 2011 г.

How to throttle bandwidth on a Linux network interface or app?

trickle should do what you want. If your running Ubuntu (or Debian, I think), you can install it with sudo apt-get install trickle, and then run it. trickle -s -d 10 -u 10 firefox (or so, I haven't used it in a while) would run firefox, limiting its download and upload speed to 10 kilobytes a second.

tc qdisc add dev tap0 root netem delay 50ms loss 50%
To add 20ms delay "tc qdisc add dev lo root handle 1:0 netem delay 20msec", and to remove it "tc qdisc del dev lo root"

wondershaper eth0 1000 200

суббота, 30 апреля 2011 г.

параллельный ssh

split -b 500m big.tgz big.tgz-part-

for i in `ls *-part-*`; do (sleep 3; scp -P 22 -i /root/.ssh/id_rsa $i root@target:/backup/ &); done
#or
for i in `ls *-part-*`; do (sleep 3; rsync -a --rsh "ssh -p 22 -i /root/.ssh/id_rsa" $i root@target:/backup/ &); done

четверг, 21 апреля 2011 г.

Network File Copy using SSH

Network File Copy using SSH
http://ultra.ap.krakow.pl/~bar/DOC/ssh_backup.html
Updated February 20, 2003
Created April 23, 2001
Please note that &&, ||, and -, are documented at the bottom of this page.
PUSH:

    * tar cvf - . | gzip -c -1 | ssh user@host cat ">" remotefile.gz
    * ssh target_address cat " remotefile
    * ssh target_address cat " remotefile
    * cat localfile | ssh target_address cat ">" remotefile
    * cat localfile | ssh target_address cat - ">" remotefile
    * dd if=localfile | ssh target_address dd of=remotefile
    * ssh target_address cat     * ssh target_address cat -     * ( cd SOURCEDIR && tar cf - . ) | ssh target_address "(cd DESTDIR && tar xvpf - )"
    * ( cd SOURCEDIR && tar cvf - . ) | ssh target_address "(cd DESTDIR && cat - > remotefile.tar )"
    * ( cd SOURCEDIR && tar czvf - . ) | ssh target_address "(cd DESTDIR && cat - > remotefile.tgz )"
    * ( cd SOURCEDIR && tar cvf - . | gzip -1 -) | ssh target_address "(cd DESTDIR && cat - > remotefile.tgz )"
    * ssh target_address "( nc -l -p 9210 > remotefile & )" && cat source-file | gzip -1 - | nc target_address 9210
    * cat localfile | gzip -1 - | ssh target_address cat ">" remotefile.gz


PULL:
# ssh target_address cat remotefile > localfile
# ssh target_address dd if=remotefile | dd of=localfile
# ssh target_address cat "<" remotefile >localfile
# ssh target_address cat "<" remotefile.gz | gunzip >localfile

COMPARE:
# ###This one uses CPU cycles on the remote server to compare the files:
# ssh target_address cat remotefile | diff - localfile
# cat localfile | ssh target_address diff - remotefile
# ###This one uses CPU cycles on the local server to compare the files:
# ssh target_address cat

Push: Push local file to remote server.
Pull: Pull remote file from remote server to local machine.

Of course there is always ftp, scp2, nfs, smb and other methods as well.

The above methods make a great Ghost replacement.
One can boot a system using standalone linux on a floppy, such as tomsrtbt and can then proceed to:

   1. backup the local hard drive to a remote server or
   2. download an image from the remote server and place it on the local hard drive.

RSH works just the same as SSH I'm sure, it's jut that ssh or ssh should give you better security.

Note: Compressing and then transferring data is faster than transferring uncompressed data. Use compression before sending data over the wire to achieve faster data transfer speeds.

localfile and remotefile can be files, directories, images, hard drive partitions, or hard drives.
Moving files around on local filesystem:

    * ( cd SOURCEDIR && tar cf - . ) | (cd DESTDIR && tar xvpf - )

FTP VIEW:

    * ftp> get file.gif "| xv -"
    * ftp> get README "| more"

FTP PUSH:

    * ftp> put "| tar cvf - ." myfile.tar
    * ftp> put "| tar cvf - . | gzip " myfile.tar.gz

FTP PULL:

    * ftp> get myfile.tar "| tar xvf -"

Pipes and Redirects:

    * zcat Fig.ps.Z | gv -
    * gunzip -c Fig.ps.gz | gv -
    * tar xvf mydir.tar
    * tar xvf - < mydir.tar
    * cat mydir.tar | tar xvf -
    * tar cvf mydir.tar .
    * tar cvf - . > mydir.tar
    * tar cf - . | (cd ~/newdir; tar xf -)
    * gunzip -c foo.gz > bar
    * cat foo.gz | gunzip > bar
    * zcat foo.gz > bar
    * gzip -c foo > bar.gz
    * cat foo | gzip > bar.gz
    * cat foo | gzip > bar.gz

SSH Keys
see http://www.cpqlinux.com/sshkeys.html
Explanation of &&, ||, and -
&& is shorthand for "if true then do"
|| is shorthand for "if false then do"
These can be used separately or together as needed. The following examples will attempt
to change directory to "/tmp/mydir"; you will get different results based on whether
"/tmp/mydir" exists or not.
cd /tmp/mydir && echo was able to change directory
cd /tmp/mydir || echo was not able to change directory
cd /tmp/mydir && echo was able to change directory || echo was not able to change to directory
cd /tmp/mydir && echo success || echo failure
cd /tmp/mydir && echo success || { echo failure; exit; }

The dash "-" is used to reference either standard input or standard output. The context in which the dash is used is what determines whether it references standard input or standard output.
Homepage: http://www.cpqlinux.com
Site Map: http://www.cpqlinux.com/sitemap-date.html


четверг, 31 марта 2011 г.

rtmp dump

Для начала скачиваем rtmpdump (берем последнюю версию) распаковываем
tar xvf rtmpdump-2.3.tgz
cd rtmpdump*
Копилируем
make
если появляются ошибки типа "No such file or directory", значит в вашей системе не хватает необходимых библиотек. Доустанавливаем необходимое: мне не хватало openssh/ssh.h
$aptitude search ssh
...
libssh-dev # <=  необходим пакет с суффиксом -dev (это исходные коды)
...
$# ставим 
$sudo aptitude install libssh-dev
$# опять пробуем собрать rtmpdump
$make
Если удачно пакет собрался, то в папке найдете rtmpdump. Устанавливаем ему права на запуск
$ chmod +x rtmpdump

А теперь по шагам 1) start wireshark
$ sudo wireshark 
Запускаем захват снифиринг пакетов на сетевом интерфейсе подключенном к инету (обычно eth0)
в ФИльтер пишем Filter: rtmpt
2) Теперь переключаемся в браузер и открываем нужный ролик, нажимаем Play. Переключаемся в wireshark и видим в первых строках Handshake. По этой строке правой клавишей мыши и выбираем Follow tcp
3) в открывшемся окне запускаем поиск и ищем слова "connect" или "app" или "play" (мне обычно хватает поиска по play) Find: "connect" "app" "play"

4) Теперь в папке скопилированного rtmpdump создаем скрипт (можно любым редактором, я использую nano)
$ nano run.sh
в файл вставляем
#!/bin/sh
SERVER="rtmp://video-3-1.rutube.ru:1935/rutube_vod_2/_definst_"
FILENAME="mp4:vol24/movies/6f/6d/6f6d7247b6d61bb5999b7bfe60aac8db.mp4"
# url берем прямо с адресной строки браузера
URL="http://rutube.ru/tracks/3194354.html?v=6f6d7247b6d61bb5999b7bfe60aac8db"
#адрес плаера, можно взять или из исходного кода страницы, или из окна Follow tcp снифера (все значения находится в соседних строках)
PLAYER="http://rutube.ru/player.swf"
# искомый файл в формате flv
OUTFILE="v.flv"

./rtmpdump -r $SERVER -t $SERVER -y $FILENAME -p $URL -s $PLAYER -o $OUTFILE
из Follow tcp окна заменяем соответсвующие переменные на значение вашего ролика

вместо wireshark можно

$ sudo cat /proc/kcore | strings | awk 'length > 20' | grep rtmp | grep -o 'rtmp:[^"]*' | grep ".mp4"
или tcpdump

ИЛИ rtsp
$ mencoder rtsp://yatv.chanson.cdnvideo.ru:554/chanson-live/shansontv.sdp -oac mp3lame -lameopts cbr:br=56 -ovc x264 -x264encopts bitrate=100 -rtsp-stream-over-tcp -o F.avi
ИЛИ
$ mplayer -noframedrop -dumpfile out.rm -dumpstream rtsp://yatv.chanson.cdnvideo.ru:554/chanson-live/shansontv.sdp

VLC
$ cvlc rtsp://yatv.chanson.cdnvideo.ru:554/chanson-live/shansontv.sdp :sout=#transcode{vcodec=h264,vb=768,ab=64,acodec=mp3,samplerate=44100,deinterlace,high-priority}:std{access=http,dst=0.0.0.0:8080/stream.flv} 

среда, 23 марта 2011 г.

linux audio over network

Звук берем через pulseaudio server
находим название аудио устройства:
$ pactl list | grep alsa_out
Name: alsa_output.pci-0000_00_07.0.analog-stereo
Monitor Source: alsa_output.pci-0000_00_07.0.analog-stereo.monitor # - это аудиовыход который нужен
Name: alsa_output.pci-0000_00_07.0.analog-stereo.monitor
Monitor of Sink: alsa_output.pci-0000_00_07.0.analog-stereo
запись в файл
$ pacat -r -d alsa_output.pci-0000_00_07.0.analog-stereo.monitor | sox -t raw -r 44100 -s -L -b 16 -c 2 - output.wav
звук по сети
pacat -r -d alsa_output.pci-0000_00_1b.0.analog-stereo.monitor | ssh user@192.168.1.1 "play -t raw -r 44100 -c -s -b 16 -" 
или через netcat
на стороне сервера
pacat -r -d alsa_output.pci-0000_00_1b.0.analog-stereo.monitor | nc -l 8008
на стороне клиента
nc 192.168.1.1 8008 | pv -b | pacat -p --latency-msec=5000 --process-time-msec=5000 



PS: так и несмог избавиться от запаздывания звука на 2-5сек на стороне клиента :(

вторник, 23 ноября 2010 г.

extracting flv from a rtmp stream

There are several tools to create flv files from a rtmp stream in linux, two of them being rtmpdump and its fork flvstreamer.
I tried to retrieve a stream where i constantly got ping messages in the process and it just stopped, so i looked for alternative ways.
The one i found was this huge script, which did crash on me: http://ubuntuforums.org/showthread.php?t=1159309
I was unwilling to search for the error or analyze the stream myself, so i came up with the following solution:

  1. capture stream with tcpdump
  2. extract streaming data with tcpflow
  3. pipe data through netcat
  4. connect rtmpdump to netcat
  5. ???
  6. profit!
sudo tcpdump -i ~device~ -p -s 0 -w ~dumpfile~ -v tcp src port 1935
tcpflow ~dumpfile~
# or use wireshrack like that http://www.youtube.com/watch?v=hNe70CbTlng

cat ~streamfile~ |netcat -l 1935&
rtmpdump -r "rtmp://localhost/streamer/stream.flv" -o 


Works quite reliable for me and is not as much code as the script which does not work.
If you end up downloading huge masses of files you can check them using flvtool2 with this script:

#!/bin/sh
if [ "$1" = "" ]
then
 echo "no filename given"
 exit
fi
if [ $(stat -c%s "$1") -eq 0 ]
then
 echo false
 exit
fi
if [ $(stat -c%s "$1") -eq `flvtool2 -P $1 /dev/null|grep filesize|sed 's/[^0-9]//g'` ]
then
 echo true
else
 echo false
fi


It returns "true" or "false", depending if projected filesize and actual filesize are equal, which means an incomplete file returns "false".

source: http://my.opera.com/dduenker/blog/show.dml/21695332

вторник, 28 сентября 2010 г.

tcpdump ascii http traffic

tcpdump -i eth0  -s0 -A -q 'dst port 80 && src host IP'

четверг, 20 мая 2010 г.

Unix Toolbox

source: http://cb.vu/unixtoolbox.xhtml
http://sleepyhead.de

Unix Toolbox


This document is a collection of Unix/Linux/BSD commands and tasks which are useful for IT work or for advanced users. This is a practical guide with concise explanations, however the reader is supposed to know what s/he is doing.




Unix Toolbox revision 14.2

The latest version of this document can be found at http://cb.vu/unixtoolbox.xhtml. Replace .xhtml on the link with .pdf for the PDF version and with .book.pdf for the booklet version. On a duplex printer the booklet will create a small book ready to bind. This XHTML page can be converted into a nice PDF document with a CSS3 compliant application (see the script example). See also the about page.

Error reports and comments are most welcome - c@cb.vu Colin Barschel.

© Colin Barschel 2007-2009. Some rights reserved under Creative Commons.


System

Hardware | Statistics | Users | Limits | Runlevels | root password | Compile kernel | Repair grub

Running kernel and system information

# uname -a # Get the kernel version (and BSD version)
# lsb_release -a # Full release info of any LSB distribution
# cat /etc/SuSE-release # Get SuSE version
# cat /etc/debian_version # Get Debian version

четверг, 4 февраля 2010 г.

port maping


echo "1" > /proc/sys/net/ipv4/ip_forward
echo "1" > /proc/sys/net/ipv4/ip_dynaddr


port mapping
iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 3000 -j DNAT --to 192.168.1.51:3000
iptables -A FORWARD -p tcp -i eth0 -o eth1 -d 192.168.1.51 --dport 3000 -j ACCEPT

IPS (router for internet sharing)
iptables -t nat -A POSTROUTING -o eth1 -s 192.168.1.0/24 -j MASQUERADE