Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
36 total  XML / RSS feed 

SSH tunnel for mySQL

Connect to remote mysql server via ssh tunnel:

ssh -f -L 3306:127.0.0.1:3306 username@servername.com sleep 120


Should auto-disconnect when it’s no longer in use.

append a ssh public key to a remote machines keys file

// What the title says :-)

cat .ssh/id_dsa.pub | ssh user@domain.tld 'cat >> .ssh/authorized_keys'

some nix commands (from MT)

Common SSH commands for (dv) 2.0 - (dv) 3.0 Servers [ *'d items work on (ss) also ]

=========================================================================================|
This is a list of Common commands that can be run from root / SSH access.


I. Basic Commands

A. Retrieve Plesk Admin Password

cat /etc/psa/.psa.shadow

B. Change Directory (cd) *


cd /path/to/directory/

C. Listing Files/SubFolders (ls) *

ls -alh (files and subfolders listed with perms in human-readable sizes)

D. Checking Processes

ps -a top -c (process viewer - Ctrl+C to exit)

ps -auxf (process list)

E. Start/Stop Services

/etc/init.d/ start|stop|restart|status ("/etc/init.d/httpd stop" stops apache)

F. Check Bean Counters (hard and soft limits, failcounts, etc.)

cat /proc/user_beancounters




II. File System Commands (df & du are (dv)-only commands)

A. Check Total Disk Usage

df (gives physical disk usage report with % used)

B. List Files/Folders +Sizes (du)

du (lists all filesizes. takes a LONG time, dont run this)

1. du -sh * (lists all the subfolders/sizes in a dir)

C. Remove/Delete Files (rm /path/to/filename.htm) -DANGER- always verify *

1. rm -vf (force-deletes file. Dont run unless you know EXACTLY what you're doing)

2. rm -vrf (force deletes folder and all subfolders and files)

D. Copy Files (cp) *

cp filename.abc /new/path/filename.abc.123

E. Move Files (mv) *

mv filename.abc /new/path/filename.abc.123

F. Create Empty File (touch) *

touch filename.123



III. File Permissions and Ownership (dv)+(ss)

A. Change Permissions of files (chmod) *

chmod 000 filename.abc (defaults are usually 755 for folders, 644 for files)

1. Numbers correspond to users. 1st=Owner; 2nd=Group; 3rd=Other

(-rwxrwxwrx = 777, -rwxr-xr-x = 755, -rw-r--r-- = 644, etc.)

7 = Read + Write + Execute
6 = Read + Write
5 = Read + Execute
4 = Read
3 = Write + Execute
2 = Write
1 = Execute
0 = All access denied

B. Change Ownership of files (chmown) *

chown user:group filename.abc (you can see user and group w/ ls -alh)

Anytime a user creates a file, the Ownership of the file matches that user. In Plesk,
every domain that has hosting has a different user. So if you are copying files from
one domain to another, you must remember to change ownership.



IV. Checking Log Files (dv)

Log files can tell you alot about whats going on on a (dv). You can use the command:
'tail -n 100' before the logfile name to list the last 100 entries of the logfile.
Here are some of the most common:

A. Main Error Log

/var/log/messages

B. Apache Error Log

1. /var/log/httpd/error_log (main)

2. /home/httpd/vhosts/domain.com/statistics/logs/error_log (per-domain)
(May also be: /var/www/vhosts on newer dvs)

C. MySQL Logs

/var/log/mysqld.log

D. Mail Logs

/user/local/psa/var/log/maillog


**Common issues to look out for in log files**

-The main error log will not always give you all the information you want for a svc.
You may see alot of failed SSH and FTP connections, that is generally normal.

-Keep an eye out for MaxClients errors in the Apache logs if a customer is complaining
of Apache dying alot. You can check the internal KB for raising MaxClients settings.

-If a customer does not set up Log Rotation for a domain under Plesk, then Log Files
will build up and may take up alot of unneeded space. You can usually delete old log
files in Plesk, and change the Log Rotation to Daily instead of by size.

-MailLogs can show you if a customer is spamming, or if mail is coming in or out.

-MySQL Logs should be able to show you general MySQL errors such as bad connections,
or corrupted tables. Check the Int. KB for the 'myisamchk -r' repair table command.



V. Advanced Commands

A. Find. You can do alot with find. for now lets find all files over 10MB.

find . -size '+10000k' -exec ls -Shl {} ;

B. Grep. Another handy tool to get specific information

cat file | grep blah (only lists the information where the word blah is found)

C. Less/More

less filename.abc (displays the content of a file. arrows to scroll, 'q' to quit.)
more == same thing basically.

You can use the '| more' command to scroll through something page or line at a time.
'tail -n 1000 /var/log/httpd/error_log | more'

D. VI. Vi is a basic text editor. Careful what keys you hit while in vi.

vi /path/to/filename.abc

i = INSERT mode. Hit 'i' when you are ready to type in some junk.
leave INSERT mode by hitting the 'Esc' key.

:q = Quit without saving. (Make sure your not in INSERT mode)

:wq = Write file and Quit (Save).

Generate DSA Keys

// generates SSH DSA keys in ~/.ssh/

ssh-keygen -d

ssh tunnel

Quick syntax example for ssh tunelling.
ssh -l username -L 4444:alpha.hostname.com:80 dmz.hostname.com

Running Mutt w/Maildirs (not IMAP) on TxD servers via ssh

I modified Pteron's muttrc file to use my local Maildir rather than login via IMAP.

This is A) Faster/better since it cuts out the bother of an imap connection to localhost and accesses your mail directly, B) It actually works (the imap method always failed on a segfault for me at least), C) You gotta like not having to store your username/password in the clear since there's no imap login to perform D) More responsive than webmail for quick email checks, and works even when webmail doesn't.

To use, change the realname line and save with filename ".muttrc"; upload this to your home directory, then login via ssh and type "mutt".

# For TextDrive accounts (running mutt on the server)

set mbox_type=Maildir
set folder="~/Maildir/"
set spoolfile="~/Maildir/"
set mask="!^\\.[^.]"
set record="+.Sent"
set postponed="+.Drafts"

set realname="Yourname"

mailboxes `\
echo -n "+ "; \
for file in ~/Maildir/.*; do \
  box=$(basename $file); \
  if [ ! $box = '.' -a ! $box = '..' -a ! $box = '.customflags' \
      -a ! $box = '.subscriptions' ]; then \
    echo -n "+$box "; \
  fi; \
done`

macro index c "?" "open a different folder"
macro pager c "?" "open a different folder"

set allow_8bit  # Don't do any Quoted-Printable encoding on 8-bit data!
set copy=yes    # Ask me if I want to save a copy of my outgoing messages.
set delete=yes
set noaskcc
set nomark_old
set reverse_alias
set reverse_name
set reply_to
set attribution="On %d, %n wrote:"
set envelope_from
set noconfirmappend
set print=ask-no
set print_cmd="echo Nix printi printi!"
set nosave_empty
set sort=threads
set read_inc=10
set write_inc=10
set noprompt_after
set status_format="%r %v [%?M?%M/?%m] %?n?%n new, ?%?p?%p postponed, ?%?t?%t +tagged, ?%?d?%d delet ed, ?(%h:%f) %?b?%b more to go.?%> %r"

#set alias_file="~/.aliases"
set quote_regexp="^([A-Za-z ]+>|[]>:|}-][]>:|}-]*)"
set include
set hdr_format="%4C %Z %{%b %d} %-15.15n (%4l) %s"
set nomove
set tilde
set noautoedit
set pager_context=1
set pager_stop
set pipe_decode
set postponed="+postponed"
set to_chars="b .c>"

set fast_reply

color header brightcyan black .
color header yellow black Subject:
color body brightyellow black [_a-z\.\$A-Z0-9-]+@[a-zA-Z0-9\./\-]+
color body yellow black (http|ftp)://[_a-zA-Z0-9\./~\-]+
color quoted green black
color signature brightblue black
color attachment yellow black
color tree red black
color indicator black cyan
color status yellow blue
color tilde blue black

bind pager 'w' previous-page
bind pager 'j' next-line
bind pager 'k' previous-line
bind index '#' tag-entry
bind index '{' previous-thread
bind index '}' next-thread

# Headers to ignore
ignore *
unignore date from to cc subject x-mailer resent-from reply-to

Bash script to export ssh public key to a remote server

This isn't a brilliant script, but it sure can be a time saver. When I add a public key by hand I end up doing a lot more commands.

#!/bin/bash

## USAGE: add_to_server.sh remote_server

## This script will add your ssh dsa public key to remote_server's authorized_keys list, 
## assuming that everything is in it's default location

set -v                                 # verbose output
username="USERNAME"              # CHANGE ME!!!!
remote_server=$1              # assigns the first commandline argument to $remote_server


## Pipe the public key to ssh, then remotely touch the file to make sure it will be there, and concat to the end of it.
## Might work without the touch?
cat ~/.ssh/id_dsa.pub | ssh ${username}@${remote_server} "touch ~/.ssh/authorized_keys && cat - >> ~/.ssh/authorized_keys"

exit 0

Remote file editing using emacs + ssh

Get TRAMP (Transparent Remote file Access, Multiple Protocol) :
http://savannah.gnu.org/projects/tramp/


Install it :
cd ~/.emacs.d/
tar -xvzf /your/download/folder/tramp-2.X.X.tar.gz
ln -s tramp-2.X.X tramp
cd tramp
./configure --with-contrib
make
sudo make install


Configure your emacs to use it :
1. Add the following in your .emacs
;; Remote file editing via ssh
(add-to-list 'load-path "~/.emacs.d/tramp/lisp/")
(require 'tramp)
(setq tramp-default-method "ssh")

2. Launch your emacs
3. C-x C-f /[email protected]:/path/to/file

Warning :
Seems it doesn't work if no password is required to login to host (using public key for example). But not sure at all...

Enable svn+ssh remote logins

Installing Subversion for local use is general an easy install, but allowing remote access to your svn repository over SSH can be problomatic dependent upon your OS and the means taken to install.

For Darwinports and Fink on OS X the install location has to be added to users $PATHs, but there are extra steps outlined here for use of the svn+ssh means of access:

http://subversion.tigris.org/faq.html#ssh-svnserve-location

A much easier alternate is to sym link the svn binaries to a place on the default PATH (used by the SSH login):

#For Darwinports
ln -s /opt/local/bin/sv* /usr/bin/

#For Fink
ln -s /sw/bin/sv* /usr/bin/


This links all the binaries at once.

Accessing CVS on a remote server through SSH

If the repository is on a remote server and you have SSH access, then just set CVS_RSH and CVSROOT.

For example, in bash:

export CVS_RSH="ssh"
export CVSROOT=":ext:me@someserver:/path/to/repository"


In combination with ssh-agent, this works nicely.

Mute Remote Macintosh

Sometimes I am in bed and too lazy to get out to mute my G5. I can just grab my iBook, SSH into the G5 and run the following command:

osascript -e 'set volume output muted true'


brilliant!

RARing files on Mac OSX 10.4

1) Download the application called RAR at

http://files3.rarlab.com/rar/rarosx-3.5.1.tar.gz

2) decompress that file and there'll be a folder called "rar".

3) in that folder there's a file called "rar" (with no quotes or extension)

4) In Finder, go to Go > Go To Folder, and type in "/bin".

5) drag the FILE called "rar" in to that bin folder. It will ask you for your password, so go type it in and continue.

6) open the terminal and go to the directory that has the file or files you want to rar.

7A) once in the folder housing the files you want to rar, type this:

rar a FileName.rar


7B) Alternatively, you can specify which file or folder inside the folder you're in, you want to rar:

rar a FileName.rar originalfilename.whatever


8) to make a multi file rar archive, type the following instead of the above and replace where you see "####" with the file size you want each part to be, in kilobytes (kb).

rar a -v#### FileName.rar originalfilename.whatever


Search for terms in Domlogs

for files in /usr/local/apache/domlogs/*; do grep "wget" $files; done;


-OR-

cd /usr/local/apache/domlogs
grep wget *
grep lynx *
grep curl *


Replace wget with other file names/terms you might want to search for.

If that takes too long, try doing it one by one:

grep wget a*
grep wget b*
grep wget c*
grep wget d*
grep wget e*
grep wget f*
grep wget g*
grep wget h*
grep wget i*
grep wget j*
grep wget k*
grep wget l*
grep wget m*
grep wget n*
grep wget o*
grep wget p*
grep wget q*
grep wget r*
grep wget s*
grep wget t*
grep wget v*
grep wget w*
grep wget x*
grep wget y*
grep wget z*


Alternatively, if you get an error like "Argument list too long":

for i in `ls /usr/local/apache/domlogs|grep -v 'bytes_log'`; do echo "checking on $i" && grep wget /usr/local/apache/domlogs/$i && grep lynx /usr/local/apache/domlogs/$i && grep curl /usr/local/apache/domlogs/$i; done > /root/grep-domlogs-results.txt
Then simply take a look at this file /root/grep-domlogs-results.txt

Looking up recent dictionary attacks

grep "dictionary attack" /var/log/exim_mainlog

Looking into DOS and DDOS Attacks

http://etechsupport.net/forum/showthread.php?t=434

top -d2
netstat -nap | grep SYN | wc -l
netstat -nap | less


If there are many httpd processes showing up after step 1, you might be under attack. If you get high numbers for the second one, you are almost definitely under attack. Use the third one to see the IP addresses, and then ban them from the server:

iptables -A INPUT -s ip.address -j DROP


Also try the following for fixing stuff:
cd /dev/shm
ls


And delete anything that's not supposed to be there.

locate bindz
locate botnet.txt
locate dc
locate ex0.pl
locate kaiten
locate r0nin
locate udp.pl
locate ...
lsof | grep .,
locate mybot

Ban IPs from a server

iptables -A INPUT -s ip.address -j DROP

How to tail logs

tail -200 /var/log/exim_mainlog
tail -200 /usr/local/apache/logs/error_log


To watch the log get updated in real time:
tail -f /var/log/messages 

Sims 2 File Limit Fix

sudo sysctl -w kern.maxfiles=22000
sudo sysctl -w kern.maxfilesperproc=20000


Type this into Terminal in Mac OSX to fix the file size limit for The Sims 2, allowing you to have more than 5000 downloads.

Add a New Rails App (Textdrive & Lighttpd)

Based on: http://forum.textdrive.com/viewtopic.php?id=5094

Get Lighttpd working on Textdrive first (http://manuals.textdrive.com/read/book/9), then to add new Rails apps (ex: typo.domain.tld) follow the steps below...

1. ssh into your account
ssh username@servername.textdrive.com


2. Create a new directory for your rails apps (if you don't have one already):
mkdir ~/apps/ (or whatever you want to name it)


3. Move into that directory:
cd ~/apps/


4. svn checkout the app you want:
Example:
svn checkout svn://leetsoft.com/typo/trunk typo


5. Move into that new app's directory:
Example:
cd typo


6. Change the first line of appname/public/dispatch.rb and appname/public/dispatch.fcgi to:
#!/usr/local/bin/ruby18


7. Set-up MySQL database:

a.
mysql -u username -p

b.
create database textdriveusername_appname;

c.
exit;

d.
mysql -u username -p textdriveusername_appname < db/schema.mysql.sql


8. Create a symbolic link to your app's public folder, inside of your public_html folder:
ln -s /home/username/apps/appname/public /home/username/public_html/appname


9. Add an $HTTP["host"] entry into your lighttpd.conf for the new app (ex: http://textsnippets.com/posts/show/6 and http://textsnippets.com/posts/show/187)

10. Kill all your dispatch.fcgi processes and your lighttpd process (ex: ttp://textsnippets.com/posts/show/206)

11. Restart lighttpd:
/usr/local/sbin/lighttpd -f /home/username/lighttpd/lighttpd.conf


12. Navigate to http://appname.yourdomain.tld


Kill Lighttpd & dispatch.fcgi Processes

From: hhttp://forum.textdrive.com/viewtopic.php?pid=43091#p43091

Kill the processes with:
killall -9 -u your_username lighttpd
killall -9 -u your_username ruby18

...or do a
ps aux

Look for the lighttpd and ruby18 process, take note of their PID (process ID - the first number in the row) and do a:
kill -9 pid (replacing pid with the PID you found)


« Newer Snippets
Older Snippets »
36 total  XML / RSS feed