Copy Text From a File in Terminal

If you just want to quickly copy the text of a file to the clipboard while in terminal you can just use:

cat [filename]

That will display the full text of the file to the terminal and you can just highlight the text and copy.

One case where this can be useful is as a quick and simple way to copy text to the clipboard of your laptop when you ssh into a remote server. If contents of the file are larger than a screen it can be difficult to scroll and copy the text you want to copy without using the cat command.

Related: How to Dump SQL Result to a Text File Using the command lineLocking and Unlocking a User in UbuntuHow to Manually Run Cron Tasks

As a reminder: The intention for this site is quick and easy sample code and syntax reminders. I frequently forget the basic syntax of some thing I donโ€™t use frequently and at times find it hard to find the simple basic information I want.

Some Quick cli Syntax for Postgres

How to Dump SQL result to a text file using cli

> psql -U postgres -d [database_name] -c ‘SELECT * FROM users’

How to exit postgres command-line utility psql
Type \q and then press ENTER to quit psql

Reset Root Password on MySQL Database
Notice that in PostgreSQL superuser is called postres (not root). If you forgot superuser password, you can reset it this way:

edit file pg_hba.conf

> sudo vim /etc/postgresql/9.3/main/pg_hba.conf

and find there a line similar to:

# TYPE  DATABASE        USER            ADDRESS                 METHOD
local   all             postgres                                md5

md5 here means that postgres asks for password. If there is this line then replace
md5 with peer, if there is no this line then add it

local   all             postgres                                peer

save the file, exit and reload postgresql service to pick up the updated configuration:

> sudo service postgresql reload

Then you should be able to get access to psql without providing a password this way:

> sudo -u postgres psql

In psql you can change user password using this command:

ALTER USER postgres PASSWORD 'new password';

PostgreSQL performance and monitoring

switch current database

\connect database_name or \c database_name

you can user autocomplete by pressing [tab]

list tables in current database

\dt

create a new database and import tables, data from a dump
in psql

CREATE DATABASE some_database

create a dump (in terminal)

> pg_dump dbname > outfile

You may notice that no password is used. That is because with Postgres you can setup a password file that is used to verify your access as such:

> vim ~/.pgpass

Then (format is hostname:port:database:username:password):

localhost:5432:mydbname:postgres:mypass
[ctrl-x] then confirm with y, then hit [enter]

save and exit

> chmod 600 ~/.pgpass

restore a dump (in terminal)

> psql dbname < infile

more details on dump-restore

create a user (it sql)

CREATE USER tester WITH PASSWORD 'test_password';
GRANT ALL PRIVILEGES ON DATABASE "test_database" to tester;

notice difference in quotation marks – in first case it must be single quotation mark ‘ and in the second case – double quotation mark “, otherwise PostgreSQL raises a syntax error

restart PostgreSQL

> sudo service postgresql restart

other regular service actions available too – [force-reload, reload, start, status, stop]

Also for Nginx (unrelated to this post really), Restart Nginx

sudo service nginx restart
other regular service actions available too – [force-reload, reload, start, status, stop]
reload only reloads configuration files, without stopping a service (which restart does)

Related: How to Dump SQL Result in MySQL to a Text File Using cliReset Root Password on MySQL DatabaseSome MySQL cli Syntax

Locking and Unlocking a User in Ubuntu

To lock a user in Ubuntu sudo usermod –expiredate 1 [username] Substitute the user’s username where username is shown below.

[code]sudo usermod –expiredate 1 username[/code]

This also can be shortened to

[code]sudo usermod -e 1 username[/code]

To unlock a user

[code]sudo usermod -e -1 username[/code]

This will disable the user both from accessing via password and from accessing via a private key.

You can also expire a user at a future date using

[code]sudo usermod -e YYYY-MM-DD username[/code]

To expire a password and force a user to enter a new password

[code]sudo passwd -e YYYY-MM-DD username[/code]

Related: Managing Users in UbuntuReset Root Password on MySQL DatabaseDonโ€™t Copy-Paste Directly from Website to Terminal

How to Manually Run Cron Tasks

To manually run cron tasks you can use the run-parts command in Linux.

So to run your cron-weekly, for example, to test that a fix you just made runs without error (this is what I just did, in fact)

run-parts /etc/cron-weekly

run-parts will run all the executables in a directory (you must point at the directory). So if you have several files in cron-weekly to run, you can’t just point to one of the files.

You may run into environmental differences running the script as a different user than the cron test runs at, so you can run as that user if needed. You need to be aware this is a quick and simple way of testing part of the process but it doesn’t do a perfect job of testing if it works as a cron task. But it will let you catch some failures quickly and fix them in time for the actual cron task to run. So do check that the everything works after the real cron job runs.

This is just the kind of thing I said I would put in this blog. Simple stuff but things I forget – so I put it here to remember and maybe help out others, like me, that need really basic tips.

If you have a cron task item (or have setup the whole task this way) that is just a script and you just want to test that 1 item you may run the script directly. For example (for a Linux shell script):

sh /etc/cron.weekly/your_crontask_script.sh

Related: Updates Needed When Upgrading from Apache 2.2 to 2.4Rsync to copy Files Between Servers and ComputersBash Profile Adjustments for Scrolling HistoryChecklist: Setting Up a New Domain on VPS

Compare WordPress Files on Server to Proper WordPress Version

Sadly one of the hassles in managing your own WordPress blog is dealing with people that use your blog to serve spam content. These hacks can insert spam links into your pages and posts or create spam directories that are completely their own content on your domain.

There are many issues to deal with in re-establishing control of your server; but that isn’t the scope of this post.

This is just a tips if you are troubleshooting to try and determine what is going on. Often your server has been hacked to allow uploaded php pages to be added or for WordPress php files to be edited.

One way to track down if the files have been changed or new ones added is to compare the WordPress files on your server to the current files for a fresh WordPress install. This assumes your blog is using the current version, which hopefully it is because on the big improvement WordPress made is to make those updates automatic. That greatly reduces the chance to have WordPress be the vector to infecting your server. If you were using a older version then just compare to the field for that version from the WordPress server.

If you don’t have a current backup I would make a backup before I tried this. Obviously, don’t make any deletions or changes to your server unless you understand what you are doing. You can create big problems for yourself.

You can use the diff command to view the difference between WordPress on your sever and the fresh install from WordPress. I install the new WordPress in a new directory outside public_html. At the cli on a Ubuntu/Linux server:

[code]sudo wget http://wordpress.org/wordpress-4.0.zip
unzip wordpress-4.0.zip
diff -rq wordpress ../public_html/[/code]

wordpress-4.0.zip – replace with whatever the version is you are using.
../public_html/blog/ – replace with the path to your blog

Continue reading

How to Dump SQL Result to a Text File Using cli

Just a quick tip on how to dump a sql result to a txt file.

mysql -e “select * from [table]” -u[user] -p [database] > sqlresult.txt

For example:

[bash]mysql -e "select * from orders where product_id = 15" -uroot -p > sqlresult.txt[/bash]

Related: Some MySQL cli Syntax ExamplesBasic MySQL Performance MonitoringMySQL Performance Tuning Tips

Updates Needed When Upgrading from Apache 2.2 to 2.4

I updated from Ubuntu 12.04 to Ubuntu 14.04 on a virtual private server.

When you do that update, Apache is updated from 2.2 to 2.4. Certain changes mean that until you update the site-available configuration files no web sites will work.

The quick checklist of what you have to do for each configuration

  1. update the file to add or edit the directory details (where /var/www/curiouscatnetwork.com/public_html/ is the path to the website files on your server)
    [bash]<Directory /var/www/curiouscatnetwork.com/public_html/>
    Require all granted
    </Directory>[/bash]
    Remember if you have details needed for WordPress those instructions need to remain. I didn’t have a Directory area listed on my non-Wordpress sites.
  2. The files now need a .conf extension so move the rename/move the files to the new name
    [bash]sudo mv curiouscatnetwork.com curiouscatnetwork.com.conf[/bash]
  3. Enable the new configuration
    [bash]sudo a2ensite curiouscatnetwork.com.conf[/bash]
  4. Reload apache to reload the new configuration
    [bash]sudo service apache2 reload[/bash]

More details from Linode.

The upgrade to Ubuntu 14.04 LTS was interrupted (I quit a window using the wrong command – oops). Luckily it wasn’t a big deal. I was able to delete the lock file.

[bash]sudo rm /var/lib/dpkg/lock[/bash]

Then trying to update again

[bash]sudo apt-get dist-upgrade[/bash]

gave a message telling me what command to use to have the upgrade continue.

[bash]sudo dpkg –configure -a[/bash]

which seemed to work fine.

Related: Bash Profile Adjustments, Scrolling HistoryChecklist: Setting Up a New Domain on VPSModSecurity: Adjustments for WordPress

Reset Root Password on MySQL Database

How to reset the root password on a MySQL database.

Stop mysql using this command:

[bash]sudo /etc/init.d/mysql stop[/bash]

Because you are not checking user privledges at this point, it’s safest to disable networking. Then, start the mysqld demon process using the –skip-grant-tables option using

[bash]sudo /usr/sbin/mysqld –skip-grant-tables –skip-networking &[/bash]

Next, start the mysql client process using this command:

[bash]mysql -u root[/bash]

from the mysql prompt execute this command to be able to change any password

[bash]FLUSH PRIVILEGES;[/bash]

Then reset/update your password

[bash]SET PASSWORD FOR root@’localhost’ = PASSWORD(‘password’);[/bash]

Related: Turn It Off and On Again (WordPress Loses Database Connection)Some MySQL cli syntax examplesKeeping Your Hosted Ubuntu Web Server Software Up to Date

Rsync to copy Files Between Servers and Computers

I found rsync when I wanted to use scp to copy files to a server but not overwrite files already there. Rsync is actually more efficient no matter what (it seems) but it is really great if there are a bunch of duplicate files (Rsync will just skip them).

To copy files from your current computer to a server:

rsync -azv -r ssh [directory] [username]@remotehost:[location]

[bash]$ sudo rsync -azv -e ssh directory-on-my-computer/ [email protected]:~/files/go/here[/bash]

a = archive mode
z = compress file data
v = verbose
r = recurse through subdirectories and copy all of them

Compressing file data saves bandwidth so if that is an issue it is another big win over scp. And in my reading it seems rsync can restart a broken file transfer in process (while scp you have to redo the whole file transfer).

To copy from the server to your computer just reverse the order of the locations. And you can even just put in two addresses not on your current computer and copy between then.

As a reminder, I realize this blog is made up of stuff that is obvious to a large number of people. It is really aimed at me (so I can quickly find what I found before), and to a lessor extent others like me (who use cli some but are not system administrators or programmers to any significant extent).

Related: Making Sure You Donโ€™t Run Out of Space on Your VPSBash Profile Adjustments (Scrolling History)Customizing the Command Prompt for Terminal in Ubuntu

Turn It Off and On Again

I had a WordPress blog lose the database connection. As I tried to troubleshoot it I rapidly got to the point of thinking that maybe just rebooting the server would fix things – since no changes had been made that should cause the database connection to be lost. But also I figured I couldn’t be so lucky that such a simple thing would work.

I tried to log into the database using the cli and it was failing. MySQL was still running – according to top. I have automated security updates setup for the VPS server running Ubuntu. My thought now is those updates somehow messed things up to the extent the server database connections somehow wasn’t working. I sure hoped that was the case.

I rebooted and hoped.

After a bit I was able to see that it was working.

When I went to reboot I noticed I hadn’t rebooted in a long time. My guess is I might have the automated security updates setup wrong on this server (maybe it is installing more than just the security updates), I’ll check. I have not had this problem before with other servers, obviously breaking a database in this way would cause lots of problems on production machines so I tend to think it is more likely I messed something up than this is a likely outcome when using automated security updates (but such things are possible which is why I think places with full time system admins and important servers rely on manual updates with professionals watching everything to be sure nothing obvious breaks).

My feeling is the longer you go with not rebooting the server the more likely some issues are to crop up (but also every reboot is more like to result in some broken thing, right then, than doing nothing so it is a tradeoff). And I could be wrong in that feeling, it is just what I guess without much evidence to support my guess.

Anyway I was very happy turning it off and on again worked. Honestly I went ahead and updated the server before I rebooted, but my guess is just turning it off and on again would have worked.

Related: Making Sure You Donโ€™t Run Out of Space on Your VPSBasic MySQL Performance MonitoringWordPress error: Image could not be processed. Please go back and try again.