-
Notifications
You must be signed in to change notification settings - Fork 1
/
LinuxCommands
4385 lines (3355 loc) · 150 KB
/
LinuxCommands
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//AWS CLI Commands VIP
------------------------------------------------------------------------------------------------------------------------------------------------
//For checking internet speed on linux
wget -O speedtest-cli https://raw.github.com/sivel/speedtest-cli/master/speedtest_cli.py
chmod +x speedtest-cli
./speedtest-cli
------------------------------------------------------------------------------------------------------------------------------------------------------------
Automation Script:
MySQL 5.6, PHP 5.6, Apache 2.4, vsftp 3.
//For amazon-linux
//For log nano to /var/log/cloud-init-output.log
//Please wait 15-20 mins for installation to take place.
--------------------------------------------------------------------
--------------------------------------------------------------------
#!/bin/bash
yum update -y
yum install -y httpd24 php56 mysql56-server php56-mysqlnd
service httpd start
chkconfig httpd on
groupadd www
usermod -a -G www ec2-user
chown -R root:www /var/www
chmod 2775 /var/www
find /var/www -type d -exec chmod 2775 {} +
find /var/www -type f -exec chmod 0664 {} +
echo "<?php phpinfo(); ?>" > /var/www/html/phpinfo.php
service mysqld start
chkconfig mysqld on
yum install vsftpd -y
service vsftpd start
chkconfig vsftpd on
--------------------------------------------------------------------------------------------------------------------------------------------------------------
//For Ubuntu 14.04
#!/bin/bash
debconf-set-selections <<< 'mysql-server mysql-server/root_password password root'
debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password root'
apt-get update -y
apt-get install mysql-server-5.6 -y
apt-get install apache2 -y
add-apt-repository ppa:ondrej/php -y
apt-get update -y
apt-get install php5.6 php5.6-mcrypt php5.6-mbstring php5.6-curl php5.6-cli php5.6-mysql php5.6-gd php5.6-intl php5.6-xsl -y --force-yes
apt-get install libapache2-mod-auth-mysql
apt-get install vsftpd -y
service apache2 restart
--------------------------------------------------
//For Redhat 7.2
//for mysql use command sudo "mysql -u root" in terminal as mysql has no password.
#!/bin/bash
yum update -y
yum install httpd -y
service httpd start
rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
yum install php56w php56w-opcache -y
yum install http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm -y
yum install mysql-community-server -y
systemctl start mysqld
systemctl enable mysqld.service
yum install vsftpd ftp -y
service httpd restart
systemctl enable httpd.service
----------------------------------------------------
//For redirecting to cloudfront
Options +FollowSymlinks
RewriteEngine on
rewriterule ^wp-content/uploads/(.*)$ http://d373vo9okeg161.cloudfront.net/$1 [$
# BEGIN WordPress
# END WordPress
--------------------------------------------------------------------------
* * * * * /usr/bin/php /var/www/html/bin/magento
:run | grep -v "Ran jobs by schedule" >> /var/www/html/var/log/magento.cron.log
* * * * * /usr/bin/php /var/www/html/update/cron.php >> /var/www/html/var/log/update.cron.log
* * * * * /usr/bin/php /var/www/html/bin/magento setup:cron:run >> /var/www/html/var/log/setup.cron.log
-------------------------------------------------------------------------------------------------------------
//Ruby on rails
#rails s -b 0.0.0.0
##!/bin/bash
apt-get update -y
cd
cd myapp/
rails s -b 0.0.0.0
--------------------------------------------------------------------------------------------------------
https://calculator.s3.amazonaws.com/index.html#r=IAD&key=calc-FA1A0C93-E87F-4B7C-9E75-DBB1FD9F23C2
----------------------------------------------------------------------------------------------------------
allow_writeable_chroot=YES
----------------------------------------------------------------------------------------------------
//Print list of folder column wise
ls -l | awk '{print $9}'
---------------------------------------------------------------
//start rail server use -d to run it in background
bundle exec rails server --binding=0.0.0.0
-----------------------------------------------------------------
//Generating random password
date +%s | sha256sum | base64 | head -c 12 ; echo
//Generating random password and saving it in mysql
date +%s | sha256sum | base64 | head -c 12 >> a.txt
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password password << a.txt'
------------------------------------------------------------------------------------------------
//Getting instance ip
command="curl http://169.254.169.254/latest/meta-data/public-ipv4"
eval $command
ip=`eval $command`
echo $ip
or
ip="$(curl http://169.254.169.254/latest/meta-data/public-ipv4)"
echo $ip
----------------------------------------------------------------------------------------------------
//Changing terminal name
PROMPT_COMMAND='echo -en "\033]0;Drupal-test-sh\a"'
----------------------------------------------------------------------------------------------------
//Text find and replace
perl -pi -e 's/54.90.208.24/54.90.208.241/g' gitlab.rb
------------------------------------------------------------------------------------------------------
//Chaning ip using find and replace in ubuntu - gitlab using shell
#!/bin/bash
ip="$(curl http://169.254.169.254/latest/meta-data/public-ipv4)"
cd /etc/gitlab/
sed -i -e 's/12345/'$ip'/g' gitlab.rb
-------------------------------------------------------------------------------------------------------
// changing gitlab admin password using ruby, rails and shell script.
.sh script
#!/bin/bash
cd /opt/gitlab/embedded/service/gitlab-rails
gitlab-rails runner "eval(File.read 'pass.rb')"
.rb script
#!/usr/bin/ruby
user = User.where(id: 1).first
user.password = "#{pass}"
user.password_confirmation = "#{pass}"
user.save!
-----------------------------------------------------------------------------------------------------------
// accessing docker files and editing it using vi :login
docker exec -i -t 27d6158fdbc7 /bin/bash
then use vi to edit.
--------------------------------------------------------------------------------------------------------
// script to take ip from ruby file and replacing it with current ip in shell
#!/bin/bash
## to change the ip of gitlab and mattermost according to the current public ip$
cd /etc/gitlab
awk 'NR==11' gitlab.rb >> a.txt
cip1="$(awk '{print $2}' a.txt >> b.txt)"
sed -e 's|["'\'']||g' b.txt >> c.txt
cip2="$(cat c.txt)"
sed 's|http://||' c.txt >> d.txt
cip="$(cat d.txt)"
ip="$(curl http://169.254.169.254/latest/meta-data/public-ipv4)"
sed -i "s|$cip|$ip|g" gitlab.rb
rm a.txt b.txt c.txt d.txt
gitlab-ctl reconfigure
------------------------------------------------------------------------------------------------------------
// Script to change ip inside docker for nginx using alpine os
#!/bin/bash
cd /etc/nginx
awk 'NR==23' nginx.conf >> a.txt
cip1="$(awk '{print $2}' a.txt >> b.txt)"
#sed -e 's|["'\'']||g' b.txt >> c.txt
#cip2="$(cat c.txt)"
sed 's|:8000;||' b.txt >> c.txt
cip="$(cat c.txt)"
ip="$(curl http://169.254.169.254/latest/meta-data/public-ipv4)"
sed -i "s|$cip|$ip|g" nginx.conf
rm a.txt b.txt c.txt
----------------------------------------------------------------------------------------------------------
// How to use multiple reboot command for crontab
sudo crontab -e
@reboot /path/to/script1.sh && /path/to/script2.sh
or
all.sh script
#!/bin/bash
/path/to/script1.sh
/path/to/script2.sh
sudo crontab -e
@reboot /path/to/all.sh
-----------------------------------------------------------------------------------------------------------
// How to see cron logs in ubuntu
grep CRON /var/log/syslog or tail -f /var/log/syslog | grep CRON
or
1. Open the file
/etc/rsyslog.d/50-default.conf
2. Find the line that starts with:
#cron.*
3. uncomment that line, save the file, and restart rsyslog:
sudo service rsyslog restart
4. You should now see a cron log file here:
/var/log/cron.log
--------------------------------------------------------------------------------------------------------------
// How to check ram slots in Ubuntu 16.04LTS
sudo dmidecode -t 17
------------------------------------------------------------------------------------------------------------------------------------------------------------
// How to Remove Docker Completely
1. The uninstallation step mentions:
sudo apt-get purge -y docker-engine
sudo apt-get autoremove -y --purge docker-engine
sudo apt-get autoclean
2. The above commands will not remove images, containers, volumes, or user created configuration files on your host. If you wish to delete all images, containers, and volumes run the following command:
sudo rm -rf /var/lib/docker
3. Remove docker from apparmor.d:
sudo rm /etc/apparmor.d/docker
4. Remove docker group:
sudo groupdel docker
--------------------------------------------------------------------------------------------------------------------------------------------------------------
// How to create and implement SSL (SelfSigned) on IP on Ubuntu apache
1. sudo a2enmod ssl headers
2. sudo service apache2 restart
3. sudo mkdir /etc/apache2/ssl
4. sudo openssl req -x509 -nodes -days 99999 -newkey rsa:2048 -keyout /etc/apache2/ssl/apache.key -out /etc/apache2/ssl/apache.crt
5. sudo nano /etc/apache2/sites-available/default-ssl.conf
Find the section:
VirtualHost _default_:443
Then, find:
ServerAdmin webmaster@localhost
And add the following Virtual Host configuration on the next line:
ServerName kb.fakedomainname.com:443
6. Verify that the following variables are set appropriately in the same file:
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/apache.crt
SSLCertificateKeyFile /etc/apache2/ssl/apache.key
7. Activate the virtual host with the command:
a2ensite default-ssl
Then restart Apache once more:
service apache2 restart
---------------------------------------------------------------------------------------------------------------------------------------------------------------
// How to redirect http to https on IP address in ubuntu (apache2)
1. sudo nano /etc/apache2/sites-available/000-default.conf
<VirtualHost 192.168.0.100:80>
ServerName example.com/
Redirect / https://example.com/
</VirtualHost>
---------------------------------------------------------------------------------------------------------------------------------------------------------------
// Scripts for Kanboard/ Yii2.0 AMI
Here, I have scripted for php interactive shell and accessed DB and automated the user password.
1. pass.sh (Main Script)
#!/bin/bash
bash phprun.sh;
sleep 5s;
p="$(cat pass.txt)"
mysql -u "kanboard" -p"root" -D "kanboard" -e "UPDATE users SET password='$p' WHERE username='admin';"
2. phpcode.php (to run php script for password)
<?php
$id=exec("curl http://169.254.169.254/latest/meta-data/instance-id");
$pass=password_hash($id, PASSWORD_DEFAULT);
file_put_contents('/var/www/html/pass.txt', $pass);
?>
3. phprun.sh (to run php script)
#!/bin/bash/php
php phpcode.php
4. kanboard.sh (script for crontab)
#!/bin/bash
bash pass.sh
sleep 1m;
rm -rf pass.sh phpcode.php phprun.sh pass.txt kanboard.sh
5. /etc/rc.local
Advantages:
Used Mysql database for large set of users.
OPcache is enabled for better performance.
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//Yii2.0 advanced
1. Install LAMP-Server
2. Download Tarball of yii2.0 and extract it in /var/www/html/
3. Open requirements.php in browser and install all php extensions.
4. sudo php init
5. Create DB for yii.
6. sudo nano common/config/main-local.php (Fill the DB details)
7. sudo ./yii migrate (db tables in your db)
8. go in browser and view 2 urls: localhost/advanced/frontend/web and localhost/advanced/backend/web
9. install phpmyadmin.
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//Create DB user, db and give him permission
create database osticketdb
CREATE USER 'osticketuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL ON osticketdb.* TO 'osticketuser'@'localhost';
flush privileges;
exit;
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//apache2 index.php preference
sudo nano /etc/apache2/mods-enabled/dir.conf
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//apache2 php is not connecting or displaying #php not displaying
sudo apt install php libapache2-mod-php
sudo apt install php7.0-mbstring
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//EC2 metadata URL
curl http://169.254.169.254/latest/meta-data/
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//SCP Transfer
scp -i ~/Desktop/test.pem ~/Desktop/cv.html [email protected]:/var/www/html
scp -i ~/Desktop/bitcanopy.pem ~/Downloads/newsletter [email protected]:/var/www/html/
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//Wordpress-Installation (not verified)
sudo yum update -y
sudo yum -y install httpd mysql-server php php-mysql
sudo service httpd start
sudo service mysqld start
cd /var/www/html
sudo wget https://wordpress.org/latest.tar.gz
sudo tar -xzf /var/www/html/latest.tar.gz
cd wordpress/
sudo mv * ../
cd ..
sudo mysql -e "create database wordpress; create user 'wp-user'@'localhost' identified by 'wp-password'; grant all privileges on wordpress . * to 'wp-user'@'localhost'; flush privileges;"
sudo mysqladmin -u root password 'root'
sudo mv /var/www/html/wp-config-sample.php /var/www/html/wp-config.php
//sudo chown -R ec2-user:root *
//sudo service httpd restart
cd ..
sudo chmod 777 -R html/.*
sed -i -e s/"define('DB_NAME', 'database_name_here');"/"define('DB_NAME', 'wordpress');"/ /var/www/html/wp-config.php && sed -i -e s/"define('DB_USER', 'username_here');"/"define('DB_USER', 'wp-user');"/ /var/www/html/wp-config.php && sed -i -e s/"define('DB_PASSWORD', 'password_here');"/"define('DB_PASSWORD', 'wp-password');"/ /var/www/html/wp-config.php
chmod 644 -R html/.*
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//Instance type name
dirtmcg
D- density
i- iops
r- ram
t- burstable
m- main choice for gp apps
c- compute
g- graphics
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//magento installation
#https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-magento-on-ubuntu-14-04
//magento server ip changed
#http://magento.stackexchange.com/questions/39752/how-do-i-fix-my-base-urls-so-i-can-access-my-magento-site
//LDAP server on ubuntu
#https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-openldap-and-phpldapadmin-on-an-ubuntu-14-04-server
//SimpleSAML
#https://www.helloitsliam.com/2014/12/23/install-configure-and-test-simplesamlphp-for-authentication-testing/
//ssl on EC2
#http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/SSL-on-an-instance.html
//efs backup to s3 using attic
#https://attic-backup.org/
#http://serverfault.com/questions/796268/backup-aws-efs-to-s3/796332
//automated backup ec2
#http://www.n2ws.com/how-to-guides/automate-amazon-ec2-instance-backup.html
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//Command line instructions
///Git global setup
git config --global user.name "Administrator"
git config --global user.email "[email protected]"
///Create a new repository
git clone [email protected]:root/android-project.git
cd android-project
touch README.md
git add README.md
git commit -m "add README"
git push -u origin master
///Existing folder or Git repository
cd existing_folder
git init
git remote add origin [email protected]:root/android-project.git
git add .
git commit
git push -u origin master
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//Setup ffmpeg on CentOS 7
URL: https://www.webfoobar.com/node/17
Centos 7 64-bit.
1. ffmpeg requires libdc1394-devel and it is available in epel repository. Execute the following command to install epel repository:
rpm -Uvh http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm
Note: As of this writing the "http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm" is the latest. If this URL returns 404 error it means that new version is released, you may want to browse "http://dl.fedoraproject.org/pub/epel/7/x86_64/e/" to look for that new released version.
2. ffmpeg is available in ATRPMS Repo. The ATRPMS Repo (http://dl.atrpms.net/all/atrpms-repo-6-7.el6.x86_64.rpm) is down, we'll use mirror:
rpm -ivh https://www.mirrorservice.org/sites/dl.atrpms.net/el7-x86_64/atrpms/stable/atrpms-repo-7-7.el7.x86_64.rpm
3. Modify the atrpms.repo to update its baseurl:
nano /etc/yum.repos.d/atrpms.repo
Under [atrpms] change the baseurl and enabled
from:
baseurl=http://dl.atrpms.net/el$releasever-$basearch/atrpms/stable
enabled=1
... to:
baseurl=https://www.mirrorservice.org/sites/dl.atrpms.net/el$releasever-$basearch/atrpms/stable
enabled=0
4. Lets install now the ffmpeg by executing:
yum -y --enablerepo=atrpms install ffmpeg
5. To verify if ffmpeg is already installed:
ffmpeg -version
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//Errors
1. 500 OOPS: cannot change directory: /home/user/public_html, VSFTPD error
Solution:
That error is generated because of Selinux. Please do the following actions:
[root@sun02 vsftpd]# getenforce
Enforcing
[root@sun02 vsftpd]# getsebool -a | grep ftp
allow_ftpd_anon_write –> off
allow_ftpd_full_access –> off
allow_ftpd_use_cifs –> off
allow_ftpd_use_nfs –> off
allow_tftp_anon_write –> off
ftp_home_dir –> on (change that to on in ur case this option is off)
ftpd_disable_trans –> off
ftpd_is_daemon –> on
httpd_enable_ftp_server –> off
tftpd_disable_trans –> off
[root@sun02 vsftpd]# setsebool -P ftp_home_dir on
---------------------------------------------------------------------------------
extension=/usr/lib64/php/modules/pdo.so
extension=/usr/lib64/php/modules/pdo_mysql.so
extension=/usr/lib64/php/modules/pdo_sqlite.so
/opt/rh/php54/root/usr/lib64/php/modules/mysql.so
-----------------------------------------------------------------------------------
OR
-----------------------------------------------------------------------------------
Use the permission code to change the folder permission and owner.
to add username: useradd username
to set userpassword: passwd username
To set file permissions
Add the www group to your instance.
[ec2-user ~]$ sudo groupadd www
Add your user (in this case, ec2-user) to the www group.
[ec2-user ~]$ sudo usermod -a -G www ec2-user
Important
You need to log out and log back in to pick up the new group. You can use the exit command, or close the terminal window.
Log out and then log back in again, and verify your membership in the www group.
Log out.
[ec2-user ~]$ exit
Reconnect to your instance, and then run the following command to verify your membership in the www group.
[ec2-user ~]$ groups
ec2-user wheel www
Change the group ownership of /var/www and its contents to the www group.
[ec2-user ~]$ sudo chown -R root:www /var/www
Change the directory permissions of /var/www and its subdirectories to add group write permissions and to set the group ID on future subdirectories.
[ec2-user ~]$ sudo chmod 2775 /var/www
[ec2-user ~]$ find /var/www -type d -exec sudo chmod 2775 {} \;
Recursively change the file permissions of /var/www and its subdirectories to add group write permissions.
[ec2-user ~]$ find /var/www -type f -exec sudo chmod 0664 {} \;
Now ec2-user (and any future members of the www group) can add, delete, and edit files in the Apache document root. Now you are ready to add content, such as a static website or a PHP application.
usermod --home /var/www/ username
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//EC2 SSL error for CLI
aws ec2 describe-instances --no-verify-ssl --profile region1
----------------------------------------------------------------------------------------------------------------------------------------------------------------
//DB commands
Transfer files within server #import database
mysql -u username -p database_name < file.sql
export database
mysqldump -u username -p database_name > file.sql
To change password of current user
SET PASSWORD FOR 'username'@'localhost' = PASSWORD('mypass');
To create user and assign to specific DB
create database databasename;
CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON databasename.* TO 'username'@'localhost' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//AMI error
1. Authorized keys found
Authorized key(s) found in the following location(s):
/root/.ssh/authorized_keys:1,2
Remove all authorized keys and share an updated AMI with authorized keys removed. Additional information is available at https://aws.amazon.com/articles/0155828273219400.
2. Our scans couldn't be fulfilled. Please address all items included below.
No access to AMI
Access not granted to the AMI in the following location(s):
us-east-1
Share the AMI in the appropriate region before scanning.
Status: Bad Request
----------------------------------------------------------------------------------------------------------------------------------------------------------------
//SFTP
NOTE:: If you are installing NFS Server that will be using SFTP User. Please follow the below points.
Create SFTP User first. Then mount the External HDD to /home/sftpuser.
Once tested SFTP User through Filezilla, proceed with NFS Server Installation and Mounting NFS Drive on Client Instances.
Before you start, as a precaution open at-least two terminal access to the server. If there is any problem during the configuration / mis configuration you can always use the other terminal login to revert back the changes.
1. Create sftpuser
sudo adduser sftpuser <sftp"projectname"> E.g. sudo adduser sftpaphos
2. Create sftpusers group
sudo groupadd sftp_users
3. Add user to sftp_users group
sudo usermod -G sftp_users sftpuser
4. Jail the user to his home directory
sudo chown root:root /home/sftpuser/
sudo chmod 755 /home/sftpuser/
sudo chown sftpuser:sftpuser /home/sftpuser/site
5. Open sshd config file '/etc/ssh/sshd_config' and edit the below line
Replace Subsystem sftp /usr/lib/openssh/sftp-server with below
Subsystem sftp internal-sftp Change PasswordAuthentication 'no' to 'yes'
6. Add the below lines at the end of the file
Match Group sftp_users
X11Forwarding no
AllowTcpForwarding no
ChrootDirectory /home/sftpuser
ForceCommand internal-sftp
7. NOTE:: Restart ssh service.
sudo service ssh restart
Once you are done with the above settings please cross verify the above settings, by connecting the instance using FileZilla for SFTP and Terminal for SSH Access. The user will not be able to connect through SSH Terminal, but the same user can connect through FileZilla.
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//update and upgrade script for cron
#!/bin/bash
crontab -l > updatecron
echo "0 1 * * * apt-get update && apt-get upgrade -y" >> updatecron
crontab updatecron
rm updatecron
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//Installing LAMP
1. sudo apt-get update
2. sudo apt-get install apache2
3. sudo update-rc.d apache2 enable
4. sudo ufw allow in "Apache Full"
5. sudo apt-get install mysql-server
6. sudo apt-get install php libapache2-mod-php php-mcrypt php-mysql php-mbstring
7. sudo nano /etc/apache2/mods-enabled/dir.conf
8. sudo service apache2 restart
9. sudo nano /var/www/html/info.php // <?php phpinfo();
10. sudo rm info.php
11. sudo update-rc.d mysql enable
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//Installing Phpmyadmin Ubuntu 16.04
1. sudo apt-get update
2. sudo apt-get install phpmyadmin php-mbstring php-gettext
3. sudo phpenmod mcrypt
4. sudo phpenmod mbstring
5. sudo nano /etc/phpmyadmin/config-db.php
Enter DB Name, username and password.
6. sudo service apache2 restart
same for nginx but additional step:
sudo ln -s /usr/share/phpmyadmin/ /var/www/html/phpmyadmin
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//Script for automating mysql 5.7.16 and phpmyadmin root password
#!/bin/bash
echo Fetching instance id
iid="$(curl http://169.254.169.254/latest/meta-data/instance-id)";
echo Fetching Complete
echo changing password to instance id for mysql
mysql -u "root" -p"hello" -D "mysql" -e "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('$iid');"
echo Password changed for mysql
--------------------------------------------------------------------------------------------------------------------------------------------------------------
//Implement SSL on Ubuntu 16.04 LTS Apache
1. sudo apt-get update
2. sudo apt-get upgrade -y
3. sudo a2enmod ssl
4. sudo service apache2 restart
5. sudo mkdir /etc/apache2/ssl
6. sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/apache2/ssl/apache.key -out /etc/apache2/ssl/apache.crt
7. sudo nano /etc/apache2/sites-available/default-ssl.conf
8. Find these lines and change it to -- SSLCertificateFile /etc/apache2/ssl/apache.crt
SSLCertificateKeyFile /etc/apache2/ssl/apache.key
9. sudo a2ensite default-ssl.conf
10. sudo service apache2 restart
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//SFTP user (not working for /var/www/html)
1. sudo adduser sftpuser
2. sudo groupadd sftp_users
3. sudo usermod -G sftp_users sftpuser
4. sudo chown root:root /var/www/html
5. sudo chmod 755 /var/www/html
6. sudo chown sftpuser:sftpuser /var/www/html
7. sudo nano /etc/ssh/sshd_config
a. Replace text with "Subsystem sftp internal-sftp"
b. Change PasswordAuthentication 'no' to 'yes'
c. Add the below lines at the end of the file
Match Group sftp_users
X11Forwarding no
AllowTcpForwarding no
ChrootDirectory /var/www/html
ForceCommand internal-sftp
8. sudo service ssh restart
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//Debug in shell Script
bash -x ./script.sh
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//functions in shell script
echoFunction() {
echo "echo is Called"
}
fooBar() {
echo "Functions are FUN!"
}
echoFunction;
fooBar;
echoFunction;
# You call functions without (), just the function name then a semicolon.
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//store and display a variable in shell script
fooVar=$(who)
echo $fooVar
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//if-else condition in shell script
if [ $fruit = apple ]
then echo "Good, I like Apples"
elif [ $fruit = pear ]
then echo "Good, I like Pears"
elif [ $fruit = banana ]
then echo "Good, I like Bananas"
else echo "Oh no, I hate Oranges!"
fi
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//how to take input from user in shell
clear
read -p "Please enter your name : " name
echo ""
read -p "Please enter your age : " age
echo ""
read -p "Please enter your sex. Male/Female : " sex
echo ""
echo "So you're a $age year old $sex called $name"
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//shell script for snapshot creation via terminal needs python-pip and aws-cli LAMP
///https://github.com/CaseyLabs/aws-ec2-ebs-automatic-snapshot-bash
#!/bin/bash
export PATH=$PATH:/usr/local/bin/:/usr/bin
# Safety feature: exit script if error is returned, or if variables not set.
# Exit if a pipeline results in an error.
set -ue
set -o pipefail
## Automatic EBS Volume Snapshot Creation & Clean-Up Script
#
# Contact us for all your Amazon Web Services Consulting needs!
#
#
# PURPOSE: This Bash script can be used to take automatic snapshots of your Linux EC2 instance. Script process:
# - Determine the instance ID of the EC2 server on which the script runs
# - Gather a list of all volume IDs attached to that instance
# - Take a snapshot of each attached volume
# - The script will then delete all associated snapshots taken by the script that are older than 7 days
#
# DISCLAIMER: This script deletes snapshots (though only the ones that it creates).
# Make sure that you understand how the script works. No responsibility accepted in event of accidental data loss.
#
## Variable Declartions ##
# Get Instance Details
instance_id=$(wget -q -O- http://169.254.169.254/latest/meta-data/instance-id)
region=$(wget -q -O- http://169.254.169.254/latest/meta-data/placement/availability-zone | sed -e 's/\([1-9]\).$/\1/g')
# Set Logging Options
logfile="/var/log/ebs-snapshot.log"
logfile_max_lines="5000"
# How many days do you wish to retain backups for? Default: 7 days
retday="10"
retention_days="$retday"
retention_date_in_seconds=$(date +%s --date "$retention_days days ago")
## Function Declarations ##
# Function: Setup logfile and redirect stdout/stderr.
log_setup() {
# Check if logfile exists and is writable.
( [ -e "$logfile" ] || touch "$logfile" ) && [ ! -w "$logfile" ] && echo "ERROR: Cannot write to $logfile. Check permissions or sudo access." && exit 1
tmplog=$(tail -n $logfile_max_lines $logfile 2>/dev/null) && echo "${tmplog}" > $logfile
exec > >(tee -a $logfile)
exec 2>&1
}
# Function: Log an event.
log() {
echo "[$(date +"%Y-%m-%d"+"%T")]: $*"
}
# Function: Confirm that the AWS CLI and related tools are installed.
prerequisite_check() {
for prerequisite in aws wget; do
hash $prerequisite &> /dev/null
if [[ $? == 1 ]]; then
echo "In order to use this script, the executable \"$prerequisite\" must be installed." 1>&2; exit 70
fi
done
}
# Function: Snapshot all volumes attached to this instance.
snapshot_volumes() {
for volume_id in $volume_list; do
log "Volume ID is $volume_id"
# Get the attched device name to add to the description so we can easily tell which volume this is.
device_name=$(aws ec2 describe-volumes --region $region --output=text --volume-ids $volume_id --query 'Volumes[0].{Devices:Attachments[0].Device}')
# Take a snapshot of the current volume, and capture the resulting snapshot ID
#snapshot_description="$(hostname)-$device_name-backup-$(date +%Y-%m-%d)"
snapshot_description="$instance_id-$device_name-automated-backup"
snapshot_id=$(aws ec2 create-snapshot --region $region --output=text --description $snapshot_description --volume-id $volume_id --query SnapshotId)
log "New snapshot is $snapshot_id"
# Add a "CreatedBy:AutomatedBackup" tag to the resulting snapshot.
# Why? Because we only want to purge snapshots taken by the script later, and not delete snapshots manually taken.
aws ec2 create-tags --region $region --resource $snapshot_id --tags Key=CreatedBy,Value=AutomatedBackup
done
}
# Function: Cleanup all snapshots associated with this instance that are older than $retention_days
cleanup_snapshots() {
for volume_id in $volume_list; do
snapshot_list=$(aws ec2 describe-snapshots --region $region --output=text --filters "Name=volume-id,Values=$volume_id" "Name=tag:CreatedBy,Values=AutomatedBackup" --query Snapshots[].SnapshotId)
for snapshot in $snapshot_list; do
log "Checking $snapshot..."
# Check age of snapshot
snapshot_date=$(aws ec2 describe-snapshots --region $region --output=text --snapshot-ids $snapshot --query Snapshots[].StartTime | awk -F "T" '{printf "%s\n", $1}')
snapshot_date_in_seconds=$(date "--date=$snapshot_date" +%s)
snapshot_description=$(aws ec2 describe-snapshots --snapshot-id $snapshot --region $region --query Snapshots[].Description)
if (( $snapshot_date_in_seconds <= $retention_date_in_seconds )); then
log "DELETING snapshot $snapshot. Description: $snapshot_description ..."
aws ec2 delete-snapshot --region $region --snapshot-id $snapshot
else
log "Not deleting snapshot $snapshot. Description: $snapshot_description ..."
fi
done
done
}
## SCRIPT COMMANDS ##
log_setup
prerequisite_check
# Grab all volume IDs attached to this instance
volume_list=$(aws ec2 describe-volumes --region $region --filters Name=attachment.instance-id,Values=$instance_id --query Volumes[].VolumeId --output text)
snapshot_volumes
cleanup_snapshots
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//shell script for setting retention period for snapshot LAMP
#!/bin/bash
echo "press ctrl+c to exit!!!"
echo Fetching current retention period......
a="$(sed -n 36p /var/www/html/iscripts/snapshotscript.sh >> a.txt)";
awk -F '"' '$0=$2' a.txt >> b.txt
b="$(cat b.txt)";
echo "Current retention period is $b days"
read -p "Please enter your new retention period in days : " rpd
echo "The New retention period will be $rpd days"
sed -i "36s|$b|$rpd|" /var/www/html/iscripts/snapshotscript.sh
rm a.txt
rm b.txt
c="$(find . -type f -name sed\* -exec rm {} \;)"
echo "Done !!!"
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//shell script for automating mysql password LAMP
#!/bin/bash
echo Fetching instance id......
iid="$(curl http://169.254.169.254/latest/meta-data/instance-id)";
echo Fetching Complete!!!!
echo "changing password to instance id for mysql"
mysql -u "root" -p"hello" -D "mysql" -e "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('$iid');"
echo "Password changed for mysql"
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//Repair corrupted ods file
zip -F file.ods --out repaired_file.ods
---------------------------------------------------------------------------------------------------------------------------------------------------------------
//LAMP base AMI Final Scripts
1. backup.sh
#!/bin/bash
echo Starting cron.....
crontab -l > updatecron1
echo "0 2 * * * cd /var/www/html/iscripts && bash snapshotscript.sh" >> updatecron1
crontab updatecron1
rm updatecron1
echo "updated entry in crontab"
2. remove.sh
#!/bin/bash
sleep 6m;
rm -rf /var/www/html/iscripts/delscript
rm /var/www/html/iscripts/remove.sh
3. rp.sh
#!/bin/bash
clear
echo "Press ctrl+c to exit!!!"
echo "Welcome to Snapshot Management Console"
echo Fetching current retention period......
a="$(sed -n 36p /var/www/html/iscripts/snapshotscript.sh >> a.txt)";
awk -F '"' '$0=$2' a.txt >> b.txt #How to cut string between inverted commas
b="$(cat b.txt)";
echo "Current retention period is $b days"
read -p "Please enter your new retention period in days : " rpd
echo "The New retention period will be $rpd days"
sed -i "36s|$b|$rpd|" /var/www/html/iscripts/snapshotscript.sh
rm a.txt
rm b.txt
c="$(find . -type f -name sed\* -exec rm {} \;)"
echo "Creating snapshot...."
bash /var/www/html/iscripts/snapshotscript.sh
echo "Creating cron for daily backup at 2:00 AM UTC"
echo "You can always edit the cron by typing sudo crontab -e"
bash /var/www/html/iscripts/backup.sh
echo "We have setup retention period, current snapshot creation and daily cron for you"
4. sftpuser.sh
#!/bin/bash
clear
read -p "Please enter the new password for sftpuser : " s
echo "Changing SFTP password......"
echo -e "$s\n$s" | passwd sftpuser
echo "Password changed for sftpuser!!!!"
5. update.sh
#!/bin/bash
echo "Press ctrl+c to exit"
echo Starting cron.....
crontab -l > updatecron
echo "Creating cron for daily update and upgrade at 1:00 am UTC"
echo "You can always make changes in the cron by typing sudo crontab -e"
echo "0 1 * * * apt-get update && apt-get upgrade -y" >> updatecron
crontab updatecron
rm updatecron
echo "Finished setting up cron for daily update and upgrade!!!!"
6. snapshotscript.sh
#!/bin/bash
export PATH=$PATH:/usr/local/bin/:/usr/bin
# Safety feature: exit script if error is returned, or if variables not set.
# Exit if a pipeline results in an error.
set -ue
set -o pipefail
## Automatic EBS Volume Snapshot Creation & Clean-Up Script
#
# Contact us for all your Amazon Web Services Consulting needs!
#
#
# PURPOSE: This Bash script can be used to take automatic snapshots of your Linux EC2 instance. Script process:
# - Determine the instance ID of the EC2 server on which the script runs
# - Gather a list of all volume IDs attached to that instance
# - Take a snapshot of each attached volume
# - The script will then delete all associated snapshots taken by the script that are older than 7 days
#
# DISCLAIMER: This script deletes snapshots (though only the ones that it creates).
# Make sure that you understand how the script works. No responsibility accepted in event of accidental data loss.
#
## Variable Declartions ##
# Get Instance Details
instance_id=$(wget -q -O- http://169.254.169.254/latest/meta-data/instance-id)
region=$(wget -q -O- http://169.254.169.254/latest/meta-data/placement/availability-zone | sed -e 's/\([1-9]\).$/\1/g')
# Set Logging Options
logfile="/var/log/ebs-snapshot.log"