Search This Blog

Friday, October 25, 2019

Mount Remote Network Folder Share locally in UBUNTU

This whole article is based on the below page...


https://forums.linuxmint.com/viewtopic.php?t=70187


Still I would like to summarize in short steps for mounting a remote Network Share Folder Locally.

1. Enter this into a terminal to install smbfs.
CODE: 
sudo apt-get install smbfs

2. Enter this into a terminal to add the samba goup.

CODE: 
sudo groupadd samba
3. Enter this into a terminal replacing user with your actual user name to add yourself to the samba group.
CODE: 
sudo adduser user samba
Example: For me it would be sudo adduser jason samba since my user name is jason.

4. Enter this into a terminal to edit your sudoer file.
CODE: 
sudo vim /etc/sudoers
5. Paste this into the last line of the file.
CODE: 
%samba   ALL=(ALL) /bin/mount,/bin/umount,/sbin/mount.cifs,/sbin/umount.cifs

6. Save and close the sudoer file.

7. Enter this in a terminal to create credentials for your share.

CODE: 
sudo vim /etc/samba/user
8. Paste this into the file using your the actual username and password for the share. Replacing admin with the actual username of the share and passwordwith the actual password of the share.
CODE: 
username=admin
password=password
Example: admin is the actual username of my samba share and password is the actual password of my samba share.

9. Save and close the file.

10. Enter this in a terminal to make a mount point for your share changing samba_share to whatever you want to call the folder. *A tip The fstab doesn't like spaces in folder names. Avoid them in the mount point and share folder name.
CODE: 
sudo mkdir /media/samba_share
11. Enter this into a Terminal to open your fstab.
CODE: 
sudo vim /etc/fstab
12. Add this line to your fstab to tell your system what it's mounting and where to mount it to, replacing myserver_ip_address with the actual IP of your share, in your case 192.168.0.1 and myshare with the actual path to the folder you want to mount in that share.
CODE: 
//myserver_ip_address/myshare  /media/samba_share  cifs  credentials=/etc/samba/user,noexec  0 0
13. Save and close your fstab.

14. Test your samba mount by entering this into the terminal replacing samba_share with whatever you decided to call your samba share mount point.
CODE:
sudo mount /media/samba_share
Example: I entered this to mount my samba shares. the "&&" just tells the commands to run one after the other.
CODE:
sudo mount /media/DocumentShare && sudo mount /media/MusicShare && sudo mount /media/PictureShare && sudo mount /media/VideoShare
If all goes well your share will show up as a mounted file system and be usable by your system and apps like any other drive locally attached to your computer.

Wednesday, August 5, 2015

SETUP AUTO BACKUP BATCH SCRIPT in WINDOWS using CYGWIN RSYNC SSH

 

Add Cygwin Path to Windows Environment Variable

  Follow Step 1 to 5

 

 

Rsync on Windows

Rsync is available for Windows through cygwin or as stand-alone packaged in cwrsync http://sourceforge.net/projects/sereds. This is very convenient for automated backups. Install one of them (not both) and add the path to the Windows system variables: # Control Panel -> System -> tab Advanced, button Environment Variables. Edit the "Path" system variable and add the full path to the installed rsync, e.g. C:\Program Files\cwRsync\bin or C:\cygwin\bin. This way the commands rsync and ssh are available in a Windows command shell.

Public key authentication

Rsync is automatically tunneled over SSH and thus uses the SSH authentication on the server. Automatic backups have to avoid a user interaction, for this the SSH public key authentication can be used and the rsync command will run without a password.
All the following commands are executed within a Windows console. In a console (Start -> Run -> cmd) create and upload the key as described in SSH, change "user" and "server" as appropriate. If the file authorized_keys2 does not exist yet, simply copy id_dsa.pub to authorized_keys2 and upload it.
# ssh-keygen -t dsa -N ''                   # Creates a public and a private key
# rsync user@server:.ssh/authorized_keys2 . # Copy the file locally from the server
# cat id_dsa.pub >> authorized_keys2        # Or use an editor to add the key
# rsync authorized_keys2 user@server:.ssh/  # Copy the file back to the server
# del authorized_keys2                      # Remove the local copy
Now test it with (in one line):
rsync -rv "/cygdrive/c/Documents and Settings/%USERNAME%/My Documents/" \
'user@server:My\ Documents/'

Automatic backup

Use a batch file to automate the backup and add the file in the scheduled tasks (Programs - Accessories - System Tools - Scheduled Tasks). For example create the file backup.bat and replace user@server
 Source: remote Linux server user@server:/home/abc/imp-files
 Destination: local XP machine C:\cygwin\home\xyz\backup\
 
@ECHO OFF

REM rsync the directory My Documents

SETLOCAL
SET CWRSYNCHOME=C:\cygwin\home\xyz\backup\
SET CYGWIN=nontsec

SET CWOLDPATH=%PATH%

REM uncomment the next line when using cygwin

SET PATH=%CWRSYNCHOME%\BIN;%PATH%

rsync -avzv --exclude "log" -e 'ssh ' "user@server:/home/abc/imp-files/" '/cygdrive/c/cygwin/home/xyz/backup/'

Friday, August 1, 2014

Recovering DATA from BAD (SUPERBLOC) HARD DRIVE

Hello everyone..
Just recovered my data from a BAD Hard drive of my server which just crashed suddenly.
My Autobackup script was working fine. 
But my backup script was not backing up personal home folders of users.


So first had to identify the LVS which was done by below commands

lvm vgscan lvm vgchange -ay lvm lvs

After finding the LVS finding the last superblock which will hopefully be in good condition.

mke2fs -n (note, -n) returns the superblocks:
$ sudo mke2fs -n /dev/--LVS--
mke2fs 1.42 (29-Nov-2011)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=0 blocks, Stripe width=0 blocks
61054976 inodes, 244190363 blocks
12209518 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=4294967296
7453 block groups
32768 blocks per group, 32768 fragments per group
8192 inodes per group
Superblock backups stored on blocks: 
    32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208, 
    4096000, 7962624, 11239424, 20480000, 23887872, 71663616, 78675968, 
    102400000, 214990848
Now taking the last superbloc for e2fsck

$ sudo e2fsck -b 214990848 /dev/sdb1 

After this command just mounted the LVS 
and got all my files


Had written this in a hurry...
Still hope it helps some one..
Drop me  a mail if any one requires guidance...
Thanks

Wednesday, March 19, 2014

Send Mail in Python (GMAIL & YAHOO)

Programmatically sending an email is really a good tool for developer’s paraphernalia. This is really handy when one automates task and wants to get notified by an email for success or failure. Lately I have written Python script to automate some jobs and incorporated method to send email notification. I thought to share this simple script here so my readers can get benefited.

Using local MTA-SMTP connection

Python script to send email
01
02
03
04
05
06
07
08
09
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
#!/usr/bin/env python
import smtplib
from email.mime.text import MIMEText
EMAIL_SUBJECT = "Email from Python script"
EMAIL_FROM = "notification@code4reference.com"
EMAIL_RECEIVERS = ['your_email@gmail.com']
def listToStr(lst):
    """This method makes comma separated list item string"""
    return ','.join(lst)
def send_email(msg):
    """This method sends an email"""
   
    msg_header = "From: " + EMAIL_FROM + "\n" + \
                 "To: " + listToStr(EMAIL_RECEIVERS) + "\n" + \
                 "Subject: " + EMAIL_SUBJECT + "\n"
    msg_body =  msg_header + msg
    try:
      #establish a connection with the local SMTP server.
      smtpObj = smtplib.SMTP('localhost')
      #Now send the email
      smtpObj.sendmail(EMAIL_FROM, EMAIL_RECEIVERS, msg_body)
      #Close the connection and session.
      smtpObj.quit()
    except SMTPException as error:
      print "Error: unable to send email :  {err}".format(err=error)
def main():
    """This is a simple main() function which demonstrate sending of email using smtplib."""
    send_email("Test email was generated by Python using smtplib and email libraries");
if __name__ == "__main__":
   """If this script is run as stand alone then call main() function."""
    main()
Before running this script make sure your system has Mail Transfer Agent(MTA) configured. If it is not then readthis post to configure Mail-server on Ubuntu 12.04.
If you are not interested to configure your own MTA then you can probably used the SMTP service provided by other Mail server e.g Gmail, yahoo, etc. But these service providers put some email limits to control spamming. If your application/script is sending email more than this limit then the service can detect it as spamming and may lock your account. You can find gmail email limit from here whereas Yahoo SMTP limit is provided here.

Using Gmail SMTP

Google SMTP server is located here smtp.gmail.com. According to the standard the SMTP port is 25 but Gmail doesn’t use this port instead it uses port 587. Script uses this information to establish a connection and sends an email.
01
02
03
04
05
06
07
08
09
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
#!/usr/bin/env python
from smtplib import SMTP
from smtplib import SMTPException
from email.mime.text import MIMEText
import sys
#Global varialbes
EMAIL_SUBJECT = "Email from Python script"
EMAIL_RECEIVERS = ['receiverId@gmail.com']
EMAIL_SENDER  =  'senderId@gmail.com'
GMAIL_SMTP = "smtp.gmail.com"
GMAIL_SMTP_PORT = 587
TEXT_SUBTYPE = "plain"
def listToStr(lst):
    """This method makes comma separated list item string"""
    return ','.join(lst)
def send_email(content, pswd):
    """This method sends an email"""    
     
    #Create the message
    msg = MIMEText(content, TEXT_SUBTYPE)
    msg["Subject"] = EMAIL_SUBJECT
    msg["From"] = EMAIL_SENDER
    msg["To"] = listToStr(EMAIL_RECEIVERS)
     
    try:
      smtpObj = SMTP(GMAIL_SMTP, GMAIL_SMTP_PORT)
      #Identify yourself to GMAIL ESMTP server.
      smtpObj.ehlo()
      #Put SMTP connection in TLS mode and call ehlo again.
      smtpObj.starttls()
      smtpObj.ehlo()
      #Login to service
      smtpObj.login(user=EMAIL_SENDER, password=pswd)
      #Send email
      smtpObj.sendmail(EMAIL_SENDER, EMAIL_RECEIVERS, msg.as_string())
      #close connection and session.
      smtpObj.quit();
    except SMTPException as error:
      print "Error: unable to send email :  {err}".format(err=error)
def main(pswd):
    """This is a simple main() function which demonstrates sending of email using smtplib."""
    send_email("Test email was generated by Python using smtplib and email libraries", pswd);
if __name__ == "__main__":
    """If this script is executed as stand alone then call main() function."""
    if len(sys.argv) == 2:
        main(sys.argv[1])
    else:
        print "Please provide password"
        sys.exit(0)
If scripts uses SMTP to send emails then Gmail can detect it as suspicious activity and it may ask you to change the password. This is a kind-of-annoying. To avoid such issues it always suggested to configure your own MTA.

Using Yahoo SMTP

Yahoo exposed SMTP service here smtp.mail.yahoo.com and 465 port. Unlike Gmail, It expects a SSL SMTP connection.
01
02
03
04
05
06
07
08
09
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
#!/usr/bin/env python
from smtplib import SMTP
from smtplib import SMTP_SSL
from smtplib import SMTPException
from email.mime.text import MIMEText
import sys
#Global varialbes
EMAIL_SUBJECT = "Email from Python script"
EMAIL_RECEIVERS = ['receiverId@gmail.com']
EMAIL_SENDER  =  'senderId@yahoo.com'
TEXT_SUBTYPE = "plain"
YAHOO_SMTP = "smtp.mail.yahoo.com"
YAHOO_SMTP_PORT = 465
def listToStr(lst):
    """This method makes comma separated list item string"""
    return ','.join(lst)
def send_email(content, pswd):
    """This method sends an email"""
    msg = MIMEText(content, TEXT_SUBTYPE)
    msg["Subject"] = EMAIL_SUBJECT
    msg["From"] = EMAIL_SENDER
    msg["To"] = listToStr(EMAIL_RECEIVERS)
     
    try:
      #Yahoo allows SMTP connection over SSL.
      smtpObj = SMTP_SSL(YAHOO_SMTP, YAHOO_SMTP_PORT)
      #If SMTP_SSL is used then ehlo and starttls call are not required.
      smtpObj.login(user=EMAIL_SENDER, password=pswd)
      smtpObj.sendmail(EMAIL_SENDER, EMAIL_RECEIVERS, msg.as_string())
      smtpObj.quit();
    except SMTPException as error:
      print "Error: unable to send email :  {err}".format(err=error)
def main(pswd):
    """This is a simple main() function which demonstrates sending of email using smtplib."""
    send_email("Test email was generated by Python using smtplib and email libraries", pswd);
if __name__ == "__main__":
    """If this script is executed as stand alone then call main() function."""
    if len(sys.argv) == 2:
        main(sys.argv[1])
    else:
        print "Please provide password"
        sys.exit(0)

Email with attachment

Above scripts just send an email what if you want to attach something with it. You can use the below script to attach a picture and text file with the email.

#!/usr/bin/env python
from smtplib import SMTP
from smtplib import SMTPException
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import sys


EMAIL_SUBJECT = "Email from Python script with attachment."
EMAIL_FROM = 'senderId@gmail.com'
EMAIL_RECEIVER = 'receiverId@gmail.com'
GMAIL_SMTP = "smtp.gmail.com"
GMAIL_SMTP_PORT = 587
TEXT_SUBTYPE = "plain"

def listToStr(lst):
    """This method makes comma separated list item string"""
    return ','.join(lst)

def send_email(content, pswd):
    """This method sends an email"""

    #Create the email.
    msg = MIMEMultipart()
    msg["Subject"] = EMAIL_SUBJECT
    msg["From"] = EMAIL_FROM
    msg["To"] = EMAIL_RECEIVER
    body = MIMEMultipart('alternative')
    body.attach(MIMEText(content, TEXT_SUBTYPE ))
    #Attach the message
    msg.attach(body)
    #Attach a text file
    msg.attach(MIMEText(file("code4reference.txt").read()))
    #Attach a picuture.
    msg.attach(MIMEImage(file("pic.jpg").read()))

    try:
      smtpObj = SMTP(GMAIL_SMTP, GMAIL_SMTP_PORT)
      #Identify yourself to GMAIL ESMTP server.
      smtpObj.ehlo()
      #Put SMTP connection in TLS mode and call ehlo again.
      smtpObj.starttls()
      smtpObj.ehlo()
      #Login to service
      smtpObj.login(user=EMAIL_FROM, password=pswd)
      #Send email
      smtpObj.sendmail(EMAIL_FROM, EMAIL_RECEIVER, msg.as_string())
      #close connection and session.
      smtpObj.quit()
    except SMTPException as error:
      print "Error: unable to send email :  {err}".format(err=error)

def main(pswd):
    """This is a simple main() function which demonstrate sending of email using smtplib."""
    send_email("Test email was generated by Python using smtplib and email libraries." + \
               " This email also has attachments. Please download them", pswd);

if __name__ == "__main__":
    """If this script is run as stand alone then call main() function."""
    if len(sys.argv) == 2:
        main(sys.argv[1]);
    else:
        print "Please provide the password"


------------------------------------------------------------------------------------------------------------------------
If you are interested in source code you can get it from github/code4reference
Hope this blog helped you in some way but don't than me as owner is Mr. Rakesh

Original blog url is Link