Replace ACCEPT with DROP to block port: ## open port ssh tcp port 22 ## iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 22 -j ACCEPT ## open cups (printing service) udp/tcp port 631 for LAN users ## iptables -A INPUT -s 192.168.1.0/24 -p udp -m udp --dport 631 -j ACCEPT iptables -A INPUT -s 192.168.1.0/24 -p tcp -m tcp --dport 631 -j ACCEPT ## allow time sync via NTP for lan users (open udp port 123) ## iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p udp --dport 123 -j ACCEPT ## open tcp port 25 (smtp) for all ## iptables -A INPUT -m state --state NEW -p tcp --dport 25 -j ACCEPT # open dns server ports for all ## iptables -A INPUT -m state --state NEW -p udp --dport 53 -j ACCEPT iptables -A INPUT -m state --state NEW -p tcp --dport 53 -j ACCEPT ## open http/https (Apache) server port to all ## iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT iptables -A INPUT -m state --state NEW -p tcp --dport 443 -j ACCEPT ## open tcp port 110 (pop3) for all ## iptables -A INPUT -m state --state NEW -p tcp --dport 110 -j ACCEPT ## open tcp port 143 (imap) for all ## iptables -A INPUT -m state --state NEW -p tcp --dport 143 -j ACCEPT ## open access to Samba file server for lan users only ## iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 137 -j ACCEPT iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 138 -j ACCEPT iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 139 -j ACCEPT iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 445 -j ACCEPT ## open access to proxy server for lan users only ## iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 3128 -j ACCEPT ## open access to mysql server for lan users only ## iptables -I INPUT -p tcp --dport 3306 -j ACCEPT
Friday, March 28, 2014
IPTABLES example
Wednesday, March 26, 2014
eBOOK Library Online With Free Download
I found a eBook library online with over 2 million books for your free download. This is the spirit we need in the IT world!
bookza.org
I found many interesting books here. Hope you too.20 Linux Server Hardening Security Tips
Securing your Linux server is important
to protect your data, intellectual property, and time, from the hands
of crackers (hackers). The system administrator is responsible for
security Linux box. In this first part of a Linux server security
series, I will provide 20 hardening tips for default installation of
Linux system.
original link here
OR
OR
You can configure Red hat / CentOS / Fedora Linux to send yum package update notification via email. Another option is to apply all security updates via a cron job. Under Debian / Ubuntu Linux you can use apticron to send security notifications.
To get password expiration information, enter:
Finally, you can also edit the /etc/shadow file in the following fields:
Recommend readings:
To unlock an account after login failures, run:
Note you can use passwd command to lock and unlock accounts:
Lock all empty password accounts:
You should only see one line as follows:
To disable service, enter:
OR
Use iptables to close open ports or stop all unwanted network services using above service and chkconfig commands.
You need to investigate each reported file. See reported file man page for further details.
You need to investigate each reported file and either set correct user and group permission or remove it.
You need to investigate each reported file and either assign it to an appropriate user and group or remove it.
It is a good practice to deploy any integrity checking software before system goes online in a production environment. If possible install AIDE software before the system is connected to any network. AIDE is a host-based intrusion detection system (HIDS) it can monitor and analyses the internals of a computing system.
Snort is a software for intrusion detection which is capable of performing packet logging and real-time traffic analysis on IP networks.
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!
original link here
Linux Server Hardening Checklist and Tips
The following instructions assume that you are using CentOS/RHEL or Ubuntu/Debian based Linux distribution.#1: Encrypt Data Communication
All data transmitted over a network is open to monitoring. Encrypt transmitted data whenever possible with password or using keys / certificates.- Use scp, ssh, rsync, or sftp for file transfer. You can also mount remote server file system or your own home directory using special sshfs and fuse tools.
- GnuPG allows to encrypt and sign your data and communication, features a versatile key managment system as well as access modules for all kind of public key directories.
- Fugu is a graphical frontend to the commandline Secure File Transfer application (SFTP). SFTP is similar to FTP, but unlike FTP, the entire session is encrypted, meaning no passwords are sent in cleartext form, and is thus much less vulnerable to third-party interception. Another option is FileZilla - a cross-platform client that supports FTP, FTP over SSL/TLS (FTPS), and SSH File Transfer Protocol (SFTP).
- OpenVPN is a cost-effective, lightweight SSL VPN.
- Lighttpd SSL (Secure Server Layer) Https Configuration And Installation
- Apache SSL (Secure Server Layer) Https (mod_ssl) Configuration And Installation
#1.1: Avoid Using FTP, Telnet, And Rlogin / Rsh Services
Under most network configurations, user names, passwords, FTP / telnet / rsh commands and transferred files can be captured by anyone on the same network using a packet sniffer. The common solution to this problem is to use either OpenSSH , SFTP, or FTPS (FTP over SSL), which adds SSL or TLS encryption to FTP. Type the following command to delete NIS, rsh and other outdated service:# yum erase inetd xinetd ypserv tftp-server telnet-server rsh-serve
#2: Minimize Software to Minimize Vulnerability
Do you really need all sort of web services installed? Avoid installing unnecessary software to avoid vulnerabilities in software. Use the RPM package manager such as yum or apt-get and/or dpkg to review all installed set of software packages on a system. Delete all unwanted packages.# yum list installed
# yum list packageName
# yum remove packageName
OR
# dpkg --list
# dpkg --info packageName
# apt-get remove packageName
#3: One Network Service Per System or VM Instance
Run different network services on separate servers or VM instance. This limits the number of other services that can be compromised. For example, if an attacker able to successfully exploit a software such as Apache flow, he / she will get an access to entire server including other services such as MySQL, e-mail server and so on. See how to install Virtualization software:- Install and Setup XEN Virtualization Software on CentOS Linux 5
- How To Setup OpenVZ under RHEL / CentOS Linux
#4: Keep Linux Kernel and Software Up to Date
Applying security patches is an important part of maintaining Linux server. Linux provides all necessary tools to keep your system updated, and also allows for easy upgrades between versions. All security update should be reviewed and applied as soon as possible. Again, use the RPM package manager such as yum and/or apt-get and/or dpkg to apply all security updates.# yum update
OR
# apt-get update && apt-get upgrade
You can configure Red hat / CentOS / Fedora Linux to send yum package update notification via email. Another option is to apply all security updates via a cron job. Under Debian / Ubuntu Linux you can use apticron to send security notifications.
#5: Use Linux Security Extensions
Linux comes with various security patches which can be used to guard against misconfigured or compromised programs. If possible use SELinux and other Linux security extensions to enforce limitations on network and other programs. For example, SELinux provides a variety of security policies for Linux kernel.#5.1: SELinux
I strongly recommend using SELinux which provides a flexible Mandatory Access Control (MAC). Under standard Linux Discretionary Access Control (DAC), an application or process running as a user (UID or SUID) has the user's permissions to objects such as files, sockets, and other processes. Running a MAC kernel protects the system from malicious or flawed applications that can damage or destroy the system. See the official Redhat documentation which explains SELinux configuration.#6: User Accounts and Strong Password Policy
Use the useradd / usermod commands to create and maintain user accounts. Make sure you have a good and strong password policy. For example, a good password includes at least 8 characters long and mixture of alphabets, number, special character, upper & lower alphabets etc. Most important pick a password you can remember. Use tools such as "John the ripper" to find out weak users passwords on your server. Configure pam_cracklib.so to enforce the password policy.#6.1: Password Aging
The chage command changes the number of days between password changes and the date of the last password change. This information is used by the system to determine when a user must change his/her password. The /etc/login.defs file defines the site-specific configuration for the shadow password suite including password aging configuration. To disable password aging, enter:chage -M 99999 userName
To get password expiration information, enter:
chage -l userName
Finally, you can also edit the /etc/shadow file in the following fields:
{userName}:{password}:{lastpasswdchanged}:{Minimum_days}:{Maximum_days}:{Warn}:{Inactive}:{Expire}:Where,
- Minimum_days: The minimum number of days required between password changes i.e. the number of days left before the user is allowed to change his/her password.
- Maximum_days: The maximum number of days the password is valid (after that user is forced to change his/her password).
- Warn : The number of days before password is to expire that user is warned that his/her password must be changed.
- Expire : Days since Jan 1, 1970 that account is disabled i.e. an absolute date specifying when the login may no longer be used.
# chage -M 60 -m 7 -W 7 userName
Recommend readings:
- Linux: Force Users To Change Their Passwords Upon First Login
- Linux turn On / Off password expiration / aging
- Lock the user password
- Search for all account without password and lock them
- Use Linux groups to enhance security
#6.2: Restricting Use of Previous Passwords
You can prevent all users from using or reuse same old passwords under Linux. The pam_unix module parameter remember can be used to configure the number of previous passwords that cannot be reused.#6.3: Locking User Accounts After Login Failures
Under Linux you can use the faillog command to display faillog records or to set login failure limits. faillog formats the contents of the failure log from /var/log/faillog database / log file. It also can be used for maintains failure counters and limits.To see failed login attempts, enter:faillog
To unlock an account after login failures, run:
faillog -r -u userName
Note you can use passwd command to lock and unlock accounts:
# lock account
passwd -l userName
# unlocak account
passwd -u userName
#6.4: How Do I Verify No Accounts Have Empty Passwords?
Type the following command# awk -F: '($2 == "") {print}' /etc/shadow
Lock all empty password accounts:
# passwd -l accountName
#6.5: Make Sure No Non-Root Accounts Have UID Set To 0
Only root account have UID 0 with full permissions to access the system. Type the following command to display all accounts with UID set to 0:# awk -F: '($3 == "0") {print}' /etc/passwd
You should only see one line as follows:
root:x:0:0:root:/root:/bin/bashIf you see other lines, delete them or make sure other accounts are authorized by you to use UID 0.
#7: Disable root Login
Never ever login as root user. You should use sudo to execute root level commands as and when required. sudo does greatly enhances the security of the system without sharing root password with other users and admins. sudo provides simple auditing and tracking features too.#8: Physical Server Security
You must protect Linux servers physical console access. Configure the BIOS and disable the booting from external devices such as DVDs / CDs / USB pen. Set BIOS and grub boot loader password to protect these settings. All production boxes must be locked in IDCs (Internet Data Center) and all persons must pass some sort of security checks before accessing your server. See also:#9: Disable Unwanted Services
Disable all unnecessary services and daemons (services that runs in the background). You need to remove all unwanted services from the system start-up. Type the following command to list all services which are started at boot time in run level # 3:# chkconfig --list | grep '3:on'
To disable service, enter:
# service serviceName stop
# chkconfig serviceName off
#9.1: Find Listening Network Ports
Use the following command to list all open ports and associated programs:netstat -tulpn
OR
nmap -sT -O localhost
nmap -sT -O server.example.com
Use iptables to close open ports or stop all unwanted network services using above service and chkconfig commands.
#9.2: See Also
- update-rc.d like command on Redhat Enterprise / CentOS Linux.
- Ubuntu / Debian Linux: Services Configuration Tool to Start / Stop System Services.
- Get Detailed Information About Particular IP address Connections Using netstat Command.
#10: Delete X Windows
X Windows on server is not required. There is no reason to run X Windows on your dedicated mail and Apache web server. You can disable and remove X Windows to improve server security and performance. Edit /etc/inittab and set run level to 3. Finally, remove X Windows system, enter:# yum groupremove "X Window System"
#11: Configure Iptables and TCPWrappers
Iptables is a user space application program that allows you to configure the firewall (Netfilter) provided by the Linux kernel. Use firewall to filter out traffic and allow only necessary traffic. Also use the TCPWrappers a host-based networking ACL system to filter network access to Internet. You can prevent many denial of service attacks with the help of Iptables:- CentOS / Redhat Iptables Firewall Configuration Tutorial
- Lighttpd Traffic Shaping: Throttle Connections Per Single IP (Rate Limit).
- How to: Linux Iptables block common attack.
- psad: Linux Detect And Block Port Scan Attacks In Real Time.
- Use shorewall on CentOS/RHEL or Ubuntu/Debian Linux based server to secure your system.
#12: Linux Kernel /etc/sysctl.conf Hardening
/etc/sysctl.conf file is used to configure kernel parameters at runtime. Linux reads and applies settings from /etc/sysctl.conf at boot time. Sample /etc/sysctl.conf:# Turn on execshield kernel.exec-shield=1 kernel.randomize_va_space=1 # Enable IP spoofing protection net.ipv4.conf.all.rp_filter=1 # Disable IP source routing net.ipv4.conf.all.accept_source_route=0 # Ignoring broadcasts request net.ipv4.icmp_echo_ignore_broadcasts=1 net.ipv4.icmp_ignore_bogus_error_messages=1 # Make sure spoofed packets get logged net.ipv4.conf.all.log_martians = 1
#13: Separate Disk Partitions
Separation of the operating system files from user files may result into a better and secure system. Make sure the following filesystems are mounted on separate partitions:- /usr
- /home
- /var and /var/tmp
- /tmp
- noexec - Do not set execution of any binaries on this partition (prevents execution of binaries but allows scripts).
- nodev - Do not allow character or special devices on this partition (prevents use of device files such as zero, sda etc).
- nosuid - Do not set SUID/SGID access on this partition (prevent the setuid bit).
/dev/sda5 /ftpdata ext3 defaults,nosuid,nodev,noexec 1 2
#13.1: Disk Quotas
Make sure disk quota is enabled for all users. To implement disk quotas, use the following steps:- Enable quotas per file system by modifying the /etc/fstab file.
- Remount the file system(s).
- Create the quota database files and generate the disk usage table.
- Assign quota policies.
- See implementing disk quotas tutorial for further details.
#14: Turn Off IPv6
Internet Protocol version 6 (IPv6) provides a new Internet layer of the TCP/IP protocol suite that replaces Internet Protocol version 4 (IPv4) and provides many benefits. Currently there are no good tools out which are able to check a system over network for IPv6 security issues. Most Linux distro began enabling IPv6 protocol by default. Crackers can send bad traffic via IPv6 as most admins are not monitoring it. Unless network configuration requires it, disable IPv6 or configure Linux IPv6 firewall:- RedHat / Centos Disable IPv6 Networking.
- Debian / Ubuntu And Other Linux Distros Disable IPv6 Networking.
- Linux IPv6 Howto - Chapter 19. Security.
- Linux IPv6 Firewall configuration and scripts are available here.
#15: Disable Unwanted SUID and SGID Binaries
All SUID/SGID bits enabled file can be misused when the SUID/SGID executable has a security problem or bug. All local or remote user can use such file. It is a good idea to find all such files. Use the find command as follows:#See all set user id files:
find / -perm +4000
# See all group id files
find / -perm +2000
# Or combine both in a single command
find / \( -perm -4000 -o -perm -2000 \) -print
find / -path -prune -o -type f -perm +6000 -ls
You need to investigate each reported file. See reported file man page for further details.
#15.1: World-Writable Files
Anyone can modify world-writable file resulting into a security issue. Use the following command to find all world writable and sticky bits set files:find /dir -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print
You need to investigate each reported file and either set correct user and group permission or remove it.
#15.2: Noowner Files
Files not owned by any user or group can pose a security problem. Just find them with the following command which do not belong to a valid user and a valid groupfind /dir -xdev \( -nouser -o -nogroup \) -print
You need to investigate each reported file and either assign it to an appropriate user and group or remove it.
#16: Use A Centralized Authentication Service
Without a centralized authentication system, user auth data becomes inconsistent, which may lead into out-of-date credentials and forgotten accounts which should have been deleted in first place. A centralized authentication service allows you maintaining central control over Linux / UNIX account and authentication data. You can keep auth data synchronized between servers. Do not use the NIS service for centralized authentication. Use OpenLDAP for clients and servers.#16.1: Kerberos
Kerberos performs authentication as a trusted third party authentication service by using cryptographic shared secret under the assumption that packets traveling along the insecure network can be read, modified, and inserted. Kerberos builds on symmetric-key cryptography and requires a key distribution center. You can make remote login, remote copy, secure inter-system file copying and other high-risk tasks safer and more controllable using Kerberos. So, when users authenticate to network services using Kerberos, unauthorized users attempting to gather passwords by monitoring network traffic are effectively thwarted. See how to setup and use Kerberos.#17: Logging and Auditing
You need to configure logging and auditing to collect all hacking and cracking attempts. By default syslog stores data in /var/log/ directory. This is also useful to find out software misconfiguration which may open your system to various attacks. See the following logging related articles:- Linux log file locations.
- How to send logs to a remote loghost.
- How do I rotate log files?.
- man pages syslogd, syslog.conf and logrotate.
#17.1: Monitor Suspicious Log Messages With Logwatch / Logcheck
Read your logs using logwatch or logcheck. These tools make your log reading life easier. You get detailed reporting on unusual items in syslog via email. A sample syslog report:################### Logwatch 7.3 (03/24/06) #################### Processing Initiated: Fri Oct 30 04:02:03 2009 Date Range Processed: yesterday ( 2009-Oct-29 ) Period is day. Detail Level of Output: 0 Type of Output: unformatted Logfiles for Host: www-52.nixcraft.net.in ################################################################## --------------------- Named Begin ------------------------ **Unmatched Entries** general: info: zone XXXXXX.com/IN: Transfer started.: 3 Time(s) general: info: zone XXXXXX.com/IN: refresh: retry limit for master ttttttttttttttttttt#53 exceeded (source ::#0): 3 Time(s) general: info: zone XXXXXX.com/IN: Transfer started.: 4 Time(s) general: info: zone XXXXXX.com/IN: refresh: retry limit for master ttttttttttttttttttt#53 exceeded (source ::#0): 4 Time(s) ---------------------- Named End ------------------------- --------------------- iptables firewall Begin ------------------------ Logged 87 packets on interface eth0 From 58.y.xxx.ww - 1 packet to tcp(8080) From 59.www.zzz.yyy - 1 packet to tcp(22) From 60.32.nnn.yyy - 2 packets to tcp(45633) From 222.xxx.ttt.zz - 5 packets to tcp(8000,8080,8800) ---------------------- iptables firewall End ------------------------- --------------------- SSHD Begin ------------------------ Users logging in through sshd: root: 123.xxx.ttt.zzz: 6 times ---------------------- SSHD End ------------------------- --------------------- Disk Space Begin ------------------------ Filesystem Size Used Avail Use% Mounted on /dev/sda3 450G 185G 241G 44% / /dev/sda1 99M 35M 60M 37% /boot ---------------------- Disk Space End ------------------------- ###################### Logwatch End #########################(Note output is truncated)
#17.2: System Accounting with auditd
The auditd is provided for system auditing. It is responsible for writing audit records to the disk. During startup, the rules in /etc/audit.rules are read by this daemon. You can open /etc/audit.rules file and make changes such as setup audit file log location and other option. With auditd you can answers the following questions:- System startup and shutdown events (reboot / halt).
- Date and time of the event.
- User respoisble for the event (such as trying to access /path/to/topsecret.dat file).
- Type of event (edit, access, delete, write, update file & commands).
- Success or failure of the event.
- Records events that Modify date and time.
- Find out who made changes to modify the system's network settings.
- Record events that modify user/group information.
- See who made changes to a file etc.
#18: Secure OpenSSH Server
The SSH protocol is recommended for remote login and remote file transfer. However, ssh is open to many attacks. See how to secure OpenSSH server:#19: Install And Use Intrusion Detection System
A network intrusion detection system (NIDS) is an intrusion detection system that tries to detect malicious activity such as denial of service attacks, port scans or even attempts to crack into computers by monitoring network traffic.It is a good practice to deploy any integrity checking software before system goes online in a production environment. If possible install AIDE software before the system is connected to any network. AIDE is a host-based intrusion detection system (HIDS) it can monitor and analyses the internals of a computing system.
Snort is a software for intrusion detection which is capable of performing packet logging and real-time traffic analysis on IP networks.
#20: Protecting Files, Directories and Email
Linux offers excellent protections against unauthorized data access. File permissions and MAC prevent unauthorized access from accessing data. However, permissions set by the Linux are irrelevant if an attacker has physical access to a computer and can simply move the computer's hard drive to another system to copy and analyze the sensitive data. You can easily protect files, and partitons under Linux using the following tools:- To encrypt and decrypt files with a password, use gpg command.
- Linux or UNIX password protect files with openssl and other tools.
- See how to encrypting directories with ecryptfs.
- TrueCrypt is free open-source disk encryption software for Windows 7/Vista/XP, Mac OS X and Linux.
- Howto: Disk and partition encryption in Linux for mobile devices.
- How to setup encrypted Swap on Linux.
#20.1: Securing Email Servers
You can use SSL certificates and gpg keys to secure email communication on both server and client computers:- Linux Securing Dovecot IMAPS / POP3S Server with SSL Configuration.
- Linux Postfix SMTP (Mail Server) SSL Certificate Installations and Configuration.
- Courier IMAP SSL Server Certificate Installtion and Configuration.
- Configure Sendmail SSL encryption for sending and receiving email.
- Enigmail: Encrypted mail with Mozilla thunderbird.
Other Recommendation:
- Backups - It cannot be stressed enough how important it is to make a backup of your Linux system. A proper offsite backup allows you to recover from cracked server i.e. an intrusion. The traditional UNIX backup programs are dump and restore are also recommended.
- How to: Looking for Rootkits on Linux based server.
- Howto: Enable ExecShield Buffer Overflows Protection on Linux based server.
- Subscribe to Redhat or Debian Linux security mailing list or RSS feed.
Recommend readings:
- Red Hat Enterprise Linux - Security Guide.
- Linux security cookbook- A good collections of security recipes for new Linux admin.
- Snort 2.1 Intrusion Detection, Second Edition - Good introduction to Snort and Intrusion detection under Linux.
- Hardening Linux - Hardening Linux identifies many of the risks of running Linux hosts and applications and provides practical examples and methods to minimize those risks.
- Linux Security HOWTO.
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!
Featured Articles:
- 30 Cool Open Source Software I Discovered in 2013
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012
- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop
Install XEN in Ubuntu
Introduction
Xen
is a type 1, bare-metal virtual machine monitor (or hypervisor), which
provides the ability to run one or more operating system instances on
the same physical machine. Xen, like other types of virtualization, is
useful for many use cases such as server consolidation and isolation of
production and development environments (e.g. corporate and personal
environments on the same system).
As
of Ubuntu 11.10 (Oneiric), the default kernel included in Ubuntu can be
used directly with the Xen hypervisor as the management (or control)
domain (Dom0 or Domain0 in Xen terminology).
The
rest of this guide gives a basic overview of how to set up a basic Xen
system and create simple guests. Our example uses LVM for virtual disks
and network bridging for virtual network cards. It also assumes Xen
4.1 (the version available in 12.04) and the xend toolstack. It assumes
a familiarity with general virtualization issues, as well as with the
specific Xen terminology. Please see the Xen wiki for more information.
During installation of Ubuntu
During
the install of Ubuntu for the Partitioning method choose "Guided - use
the entire disk and setup LVM". Then, when prompted to enter "Amount of
volume group to use for guided partitioning:" Enter a value just large
enough for the Xen Dom0 system, leaving the rest for virtual disks.
Enter a value smaller than the size of your installation drive. For
example 10 GB or even 5 GB should be large enough for a minimal Xen Dom0
system. Entering a percentage of maximum size (e.g. 25%) is also a
reasonable choice.
Installing Xen
Install a
64-bit hypervisor. (A 64-bit hypervisor works with a 32-bit dom0
kernel, but allows you to run 64-bit guests as well.)
sudo apt-get install xen-hypervisor-amd64
Modify
GRUB to default to booting Xen ("Xen 4.1-amd64" should be replaced with
the appropriate name, in 12.10 the line is "Ubuntu GNU/Linux, with Xen
hypervisor". The current string can be obtained by looking for one of
the menuentry lines in /boot/grub/grub.cfg. In theory the first element
created by the 20_linux_xen script):
sudo sed -i 's/GRUB_DEFAULT=.*\+/GRUB_DEFAULT="Xen 4.1-amd64"/' /etc/default/grub sudo update-grub
Set the default toolstack to xm (aka xend):
sudo sed -i 's/TOOLSTACK=.*\+/TOOLSTACK="xm"/' /etc/default/xen
Now reboot:
sudo reboot
And then verify that the installation has succeeded:
sudo xm list Name ID Mem VCPUs State Time(s) Domain-0 0 945 1 r----- 11.3
Network Configuration
This
section describes how to set up linux bridging in Xen. It assumes eth0
is both your primary interface to dom0 and the interface you want your
VMs to use. It also assumes you're using DHCP.
sudo apt-get install bridge-utils
Note if you are working with a desktop install, disable Network Manager.
sudo update-rc.d network-manager disable sudo /etc/init.d/network-manager stop
Edit /etc/network/interfaces, and make it look like this:
auto lo iface lo inet loopback auto xenbr0 iface xenbr0 inet dhcp bridge_ports eth0 auto eth0 iface eth0 inet manual
Restart networking to enable xenbr0 bridge:
sudo /etc/init.d/networking restart
The brctl command is useful for providing addition bridge information. See: man brctl
Creating vms
There are many options for installing guest images:
- xen-tools: A set of scripts for creating various PV guests
- virt-manager.org: A management system using libvirt
- Converting an existing installation
- Downloading pre-build guest images (e.g. http://wiki.xen.org/wiki/Guest_VM_Images)
Or you can manually create one, as described below.
Manually creating a PV Guest VM
In
this section we will focus on Paravirtualized (or PV) guests. PV guests
are guests that are made Xen-aware and therefore can be optimized for
Xen.
As
a simple example we'll create a PV guest in LVM logical volume (LV) by
doing a network installation of Ubuntu (other distros such as Debian,
Fedora, and CentOS can be installed in a similar way).
sudo pvs
choose your volume group (VG)
create LV
sudo lvcreate -L 4G -n ubuntu /dev/<VG>
get netboot images
choose an archive mirror https://launchpad.net/ubuntu/+archivemirrors
sudo mkdir -p /var/lib/xen/images/ubuntu-netboot cd /var/lib/xen/images/ubuntu-netboot sudo wget <mirror>/ubuntu/dists/precise/main/installer-amd64/current/images/netboot/xen/initrd.gz wget <mirror>/ubuntu/dists/precise/main/installer-amd64/current/images/netboot/xen/vmlinuz
With a specific mirror chosen:
sudo mkdir -p /var/lib/xen/images/ubuntu-netboot cd /var/lib/xen/images/ubuntu-netboot sudo wget http://mirror.anl.gov/pub/ubuntu/dists/precise/main/installer-amd64/current/images/netboot/xen/initrd.gz sudo wget http://mirror.anl.gov/pub/ubuntu/dists/precise/main/installer-amd64/current/images/netboot/xen/vmlinuz
Set up the initial guest configuration: /etc/xen/ubuntu.cfg
name = "ubuntu" memory = 256 disk = ['phy:/dev/<VG>/ubuntu,xvda,w'] vif = [' '] kernel = "/var/lib/xen/images/ubuntu-netboot/vmlinuz" ramdisk = "/var/lib/xen/images/ubuntu-netboot/initrd.gz" extra = "debian-installer/exit/always_halt=true -- console=hvc0"
Start the VM and connect to console (-c):
sudo xm create /etc/xen/ubuntu.cfg -c
Do the install.
Once installed, we can use pygrub as the bootloader.
sudo ln -s /usr/lib/xen-4.1/bin/pygrub /usr/bin/pygrub
Once the install is done, the VM will shutdown. Next change the guest config, /etc/xen/ubuntu.cfg:
name = "ubuntu" memory = 256 disk = ['phy:/dev/<VG>/ubuntu64,xvda,w'] vif = [' '] bootloader = "pygrub" #kernel = "/var/lib/xen/images/ubuntu-netboot/amd64/vmlinuz" #ramdisk = "/var/lib/xen/images/ubuntu-netboot/amd64/initrd.gz" #extra = "debian-installer/exit/always_halt=true -- console=hvc0"
Start the VM and connect to console (-c):
sudo xm create /etc/xen/ubuntu.cfg -c
Manually installing an HVM Guest VM
Download Install ISO.
sudo pvs
choose your VG
Create a LV
sudo lvcreate -L 4G -n ubuntu-hvm /dev/<VG>
Create a guest config file /etc/xen/ubuntu-hvm.cfg
builder = "hvm" name = "ubuntu-hvm" memory = "512" vcpus = 1 vif = [''] disk = ['phy:/dev/<VG>/ubuntu-hvm,hda,w','file:/root/ubuntu-12.04-desktop-amd64.iso,hdc:cdrom,r'] vnc = 1 boot="dc"
xm create /etc/xen/ubuntu-hvm.cfg vncviewer localhost:0
After the install you can optionally remove the CDROM from the config and/or change the boot order.
For example /etc/xen/ubuntu-hvm.cfg:
builder = "hvm" name = "ubuntu-hvm" memory = "512" vcpus = 1 vif = [''] #disk = ['phy:/dev/<VG>/ubuntu-hvm,hda,w','file:/root/ubuntu-12.04-server-amd64.iso,hdc:cdrom,r'] disk = ['phy:/dev/<VG>/ubuntu-hvm,hda,w'] vnc = 1 boot="c" #boot="dc"
Xen Toolstack Choices
Xen and xl
xl
is a new toolstack written from the ground up to be a replacement for
xend and xm. Xen 4.1 contains a "tech preview" version of xl that is
mostly functional, but may still contain some bugs and missing features.
As of Xen 4.2, xl will have feature parity with xend, and will be the
preferred toolstack. xend/xm are deprecated as of 4.2, and will be removed at some point.
To test xl, do the following:
sudo sed -i 's/TOOLSTACK=.*\+/TOOLSTACK="xl"/' /etc/default/xen sudo reboot sudo /etc/init.d/xend stop sudo xl list
xl and xm are very similar in functionality with a few notable exceptions: http://wiki.xen.org/wiki/XL
Xen and Libvirt
Make the following change to the xend configuration in /etc/xen/xend-config.sxp:
(xend-unix-server yes)
Restart xend:
sudo /etc/init.d/xend restart
sudo apt-get install virtinst
sudo virt-install --name ubuntu --ram 256 --disk <path to LV or disk image> --location http://mirror.clarkson.edu/fedora/linux/releases/16/Fedora/x86_64/os/
Xen and XAPI
Other tips and tricks
Create and format disk image file
sudo mkdir -p /var/lib/xen/images sudo dd if=/dev/zero of=/var/lib/xen/images/ubuntu-guest.img bs=1M seek=3096 count=0 sudo mkfs.ext4 -F /var/lib/xen/images/ubuntu-guest.img
See Also
External Links
- http://wiki.xen.org/wiki/Debian_Guest_Installation_Using_Debian_Installer - Netboot installation of PV guests
- http://wiki.xen.org/wiki/HostConfiguration/Networking - Networking configuration details from Xen.org wiki
- http://libvirt.org/uri.html#URI_file - Libvirt xend configuration
- http://wiki.xen.org/wiki/Xen_Man_Pages - Xen Man pages
- http://xenbits.xen.org/docs/unstable/man/xmdomain.cfg.5.html - xm config options
- http://xenbits.xen.org/docs/unstable/man/xl.cfg.5.html xl config options
- http://xenbits.xen.org/docs/unstable/misc/xl-disk-configuration.txt xl disk configuration
- http://serverfault.com/questions/390373/xen-4-1-host-dom0-with-blktap-disks-tapaio-not-connecting blktap issues and fixes.
Xen (last edited 2014-03-17 14:57:47 by smb)
Monday, March 24, 2014
Script: Install VirtualBox in Ubuntu
Option I
Here is the script for you to install VirtualBox 4.3 in Ubuntu:
sudo sh -c "echo 'deb http://download.virtualbox.org/virtualbox/debian '$(lsb_release -cs)' contrib non-free' > /etc/apt/sources.list.d/virtualbox.list" && wget -q http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc -O- | sudo apt-key add - && sudo apt-get update && sudo apt-get install virtualbox-4.3 dkms
I tried and found it worked in my Ubuntu LTS12.04.
Option II
This tutorial show you how to install VirtualBox in Ubuntu interactively. Further more, it shows you how to create a VM with specific settings to it.
http://www.howtoforge.com/vboxheadless-running-virtual-machines-with-virtualbox-4.1-on-a-headless-ubuntu-11.10-server
Start the virtual server:
VBoxHeadless --startvm "Ubuntu 11.10 Server"
Stop the virtual server:
VBoxManage controlvm "Ubuntu 11.10 Server" poweroff
Display server details:
VBoxManage showvminfo "Ubuntu 11.10 Server"
To see the IP address of the virtual server, go to
/root/.config/VirtualBox/VirtualBox.xml (for user root in Ubuntu)
/root/.VirtualBox/VirtualBox.xml (for user root in CentOS)
where root is the user who created the virtual server
Below is more detail about OPTION II.
http://www.howtoforge.com/vboxheadless-running-virtual-machines-with-virtualbox-4.1-on-a-headless-ubuntu-11.10-server
Version 1.0
Author: Falko Timme <ft [at] falkotimme [dot] com>
Follow me on Twitter
Last edited 01/13/2012
This guide explains how you can run virtual machines with VirtualBox 4.1 on a headless Ubuntu 11.10 server. Normally you use the VirtualBox GUI to manage your virtual machines, but a server does not have a desktop environment. Fortunately, VirtualBox comes with a tool called VBoxHeadless that allows you to connect to the virtual machines over a remote desktop connection, so there's no need for the VirtualBox GUI.
I do not issue any guarantee that this will work for you!
Then we download the VirtualBox public key...
Starting with version 4.0, VirtualBox has introduced so called "extension packs" and has outsourced some functionality like remote desktop connection support (VRDP) that was part of VirtualBox packages before version 4.0 into these extension packs. Because we need remote desktop connections to control our virtual machines, we need to install the appropriate extension pack now. Go to http://www.virtualbox.org/wiki/Downloads, and you will find a link to the following extension pack:
(Make sure you run the last command with sudo - sudo VBoxManage extpack install ... - because otherwise you will get an error like this:
Now we must add the user that will run VirtualBox (administrator in this example) to the vboxusers group:
I will now create an Ubuntu 11.10 Server VM with 512MB memory and a 10GB hard drive from the Ubuntu 11.10 Server iso image (which I have stored in /home/ubuntu-11.10-server-amd64.iso):
In addition to that copy the examplevm.vdi file from the old VDI directory to the new one (e.g. /home/administrator/.VirtualBox/VDI/examplevm.vdi).
Afterwards, you must register the imported VM:
VBoxHeadless will start the VM and a VRDP (VirtualBox Remote Desktop Protocol) server which allows you to see the VM's output remotely on another machine.
To stop a VM, run
Here is the script for you to install VirtualBox 4.3 in Ubuntu:
sudo sh -c "echo 'deb http://download.virtualbox.org/virtualbox/debian '$(lsb_release -cs)' contrib non-free' > /etc/apt/sources.list.d/virtualbox.list" && wget -q http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc -O- | sudo apt-key add - && sudo apt-get update && sudo apt-get install virtualbox-4.3 dkms
I tried and found it worked in my Ubuntu LTS12.04.
Option II
This tutorial show you how to install VirtualBox in Ubuntu interactively. Further more, it shows you how to create a VM with specific settings to it.
http://www.howtoforge.com/vboxheadless-running-virtual-machines-with-virtualbox-4.1-on-a-headless-ubuntu-11.10-server
Start the virtual server:
VBoxHeadless --startvm "Ubuntu 11.10 Server"
Stop the virtual server:
VBoxManage controlvm "Ubuntu 11.10 Server" poweroff
Display server details:
VBoxManage showvminfo "Ubuntu 11.10 Server"
To see the IP address of the virtual server, go to
/root/.config/VirtualBox/VirtualBox.xml (for user root in Ubuntu)
/root/.VirtualBox/VirtualBox.xml (for user root in CentOS)
where root is the user who created the virtual server
Below is more detail about OPTION II.
http://www.howtoforge.com/vboxheadless-running-virtual-machines-with-virtualbox-4.1-on-a-headless-ubuntu-11.10-server
VBoxHeadless - Running Virtual Machines With VirtualBox 4.1 On A Headless Ubuntu 11.10 Server
Author: Falko Timme <ft [at] falkotimme [dot] com>
Follow me on Twitter
Last edited 01/13/2012
This guide explains how you can run virtual machines with VirtualBox 4.1 on a headless Ubuntu 11.10 server. Normally you use the VirtualBox GUI to manage your virtual machines, but a server does not have a desktop environment. Fortunately, VirtualBox comes with a tool called VBoxHeadless that allows you to connect to the virtual machines over a remote desktop connection, so there's no need for the VirtualBox GUI.
I do not issue any guarantee that this will work for you!
1 Preliminary Note
I have tested this on an Ubuntu 11.10 server (host system) with the IP address 192.168.0.100 where I'm logged in as a normal user (user name administrator in this example) instead of as root.2 Installing VirtualBox
To install VirtualBox 4.1 on our Ubuntu 11.10 server, we open /etc/apt/sources.list...
sudo vi /etc/apt/sources.list
... and add the following line to it:[...] deb http://download.virtualbox.org/virtualbox/debian oneiric contrib |
wget -q http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc -O- | sudo apt-key add -
... and update our package database:
sudo apt-get update
Afterwards, we install VirtualBox 4.1 as follows:
sudo apt-get install linux-headers-$(uname -r) build-essential virtualbox-4.1 dkms
(The dkms package ensures that the VirtualBox host kernel modules are properly updated if the Linux kernel version changes.) Starting with version 4.0, VirtualBox has introduced so called "extension packs" and has outsourced some functionality like remote desktop connection support (VRDP) that was part of VirtualBox packages before version 4.0 into these extension packs. Because we need remote desktop connections to control our virtual machines, we need to install the appropriate extension pack now. Go to http://www.virtualbox.org/wiki/Downloads, and you will find a link to the following extension pack:
VirtualBox 4.1.8 Oracle VM VirtualBox Extension Pack
Support for USB 2.0 devices, VirtualBox RDP and PXE boot for Intel cards.
Download and install the extension pack as follows:Support for USB 2.0 devices, VirtualBox RDP and PXE boot for Intel cards.
cd /tmp
wget http://download.virtualbox.org/virtualbox/4.1.8/Oracle_VM_VirtualBox_Extension_Pack-4.1.8-75467.vbox-extpack
sudo VBoxManage extpack install Oracle_VM_VirtualBox_Extension_Pack-4.1.8-75467.vbox-extpack
(Make sure you grab the latest version from the VirtualBox web site.)wget http://download.virtualbox.org/virtualbox/4.1.8/Oracle_VM_VirtualBox_Extension_Pack-4.1.8-75467.vbox-extpack
sudo VBoxManage extpack install Oracle_VM_VirtualBox_Extension_Pack-4.1.8-75467.vbox-extpack
(Make sure you run the last command with sudo - sudo VBoxManage extpack install ... - because otherwise you will get an error like this:
administrator@server1:/tmp$ VBoxManage extpack install Oracle_VM_VirtualBox_Extension_Pack-4.1.8-75467.vbox-extpack
0%...
Progress state: NS_ERROR_FAILURE
VBoxManage: error: Failed to install "/tmp/Oracle_VM_VirtualBox_Extension_Pack-4.1.8-75467.vbox-extpack": The installer failed with exit code 127: Error creating textual authentication agent: Error opening current controlling terminal for the process (`/dev/tty'): No such device or address
administrator@server1:/tmp$
)0%...
Progress state: NS_ERROR_FAILURE
VBoxManage: error: Failed to install "/tmp/Oracle_VM_VirtualBox_Extension_Pack-4.1.8-75467.vbox-extpack": The installer failed with exit code 127: Error creating textual authentication agent: Error opening current controlling terminal for the process (`/dev/tty'): No such device or address
administrator@server1:/tmp$
Now we must add the user that will run VirtualBox (administrator in this example) to the vboxusers group:
sudo adduser administrator vboxusers
VirtualBox is now installed and ready to be used.3 Using VirtualBox On The Command Line
3.1 Creating A VM
To create a VM on the command line, we can use the VBoxManage command. See
VBoxManage --help
for a list of available switches and (highly recommended!) take a look at http://www.virtualbox.org/manual/ch08.html.I will now create an Ubuntu 11.10 Server VM with 512MB memory and a 10GB hard drive from the Ubuntu 11.10 Server iso image (which I have stored in /home/ubuntu-11.10-server-amd64.iso):
VBoxManage createvm --name "Ubuntu 11.10 Server" --register
VBoxManage modifyvm "Ubuntu 11.10 Server" --memory 512 --acpi on --boot1 dvd --nic1 bridged --bridgeadapter1 eth0
VBoxManage createhd --filename Ubuntu_11_10_Server.vdi --size 10000
VBoxManage storagectl "Ubuntu 11.10 Server" --name "IDE Controller" --add ide
VBoxManage storageattach "Ubuntu 11.10 Server" --storagectl "IDE Controller" --port 0 --device 0 --type hdd --medium Ubuntu_11_10_Server.vdi
VBoxManage storageattach "Ubuntu 11.10 Server" --storagectl "IDE Controller" --port 1 --device 0 --type dvddrive --medium /home/ubuntu-11.10-server-amd64.iso
VBoxManage modifyvm "Ubuntu 11.10 Server" --memory 512 --acpi on --boot1 dvd --nic1 bridged --bridgeadapter1 eth0
VBoxManage createhd --filename Ubuntu_11_10_Server.vdi --size 10000
VBoxManage storagectl "Ubuntu 11.10 Server" --name "IDE Controller" --add ide
VBoxManage storageattach "Ubuntu 11.10 Server" --storagectl "IDE Controller" --port 0 --device 0 --type hdd --medium Ubuntu_11_10_Server.vdi
VBoxManage storageattach "Ubuntu 11.10 Server" --storagectl "IDE Controller" --port 1 --device 0 --type dvddrive --medium /home/ubuntu-11.10-server-amd64.iso
3.2 Importing An Existing VM
Let's assume you have a VM called examplevm that you want to reuse on this host. On the old host, you should have a directory Machines/examplevm in the VirtualBox directory; Machines/examplevm should contain the examplevm.xml file. Copy the examplevm directory (including the examplevm.xml file) to your new Machines directory (if your user name is administrator, this is /home/administrator/.VirtualBox/Machines - the result should be /home/administrator/.VirtualBox/Machines/examplevm/examplevm.xml).In addition to that copy the examplevm.vdi file from the old VDI directory to the new one (e.g. /home/administrator/.VirtualBox/VDI/examplevm.vdi).
Afterwards, you must register the imported VM:
VBoxManage registervm Machines/examplevm/examplevm.xml
3.3 Starting A VM With VBoxHeadless
Regardless of if you create a new VM or import an old one, you can start it with the command:
VBoxHeadless --startvm "Ubuntu 11.10 Server"
(Replace Ubuntu 11.10 Server with the name of your VM.)VBoxHeadless will start the VM and a VRDP (VirtualBox Remote Desktop Protocol) server which allows you to see the VM's output remotely on another machine.
To stop a VM, run
VBoxManage controlvm "Ubuntu 11.10 Server" poweroff
To pause a VM, run
VBoxManage controlvm "Ubuntu 11.10 Server" pause
To reset a VM, run
VBoxManage controlvm "Ubuntu 11.10 Server" reset
To learn more about VBoxHeadless, take a look at
VBoxHeadless --help
and at http://www.virtualbox.org/manual/ch07.html#vboxheadless.Saturday, March 15, 2014
Apache Cordova Project for Mobile Phone App Development
The Command-Line Interface
This guide shows you how to create applications and deploy them to various native mobile platforms using thecordova
command-line
interface (CLI). This tool allows you to create new projects, build
them on different platforms, and run on real devices or within emulators. The CLI
is the main tool to use for the cross-platform workflow (See the Overview for a description
of the various workflows.) However, you can also use the CLI to initialize project code, after
which you use various platforms' SDKs and shell tools for continued development.Prerequisites
Before running any command-line tools, you need to install SDKs for each platform you wish to target. (See the Platform Guides for more details.)To add support or rebuild a project for any platform, you need to run the command-line interface from the same machine that supports the platform's SDK. The CLI supports the following combinations:
- iOS (Mac)
- Amazon Fire OS (Mac, Linux, Windows)
- Android (Mac, Linux)
- BlackBerry 10 (Mac, Linux, Windows)
- Windows Phone 7 (Windows)
- Windows Phone 8 (Windows)
- Windows 8 (Windows)
- Firefox OS (Mac, Linux, Windows)
The more likely it is that you run the CLI from different machines, the more it makes sense to maintain a remote source code repository, whose assets you pull down to local working directories.
To install the
cordova
command-line tool, follow these steps:- Download and install Node.js. Following
installation, you should be able to invoke
node
ornpm
on your command line. -
Install the
cordova
utility. In Unix, prefixing the additionalsudo
command may be necessary to install development utilities in otherwise restricted directories:
The installation log may produce errors for any uninstalled platform SDKs. Following installation, you should be able to run$ sudo npm install -g cordova
cordova
on the command line.
NOTE: The-g
flag above tells npm to install cordova globally. You may need to add the npm directory to your PATH in order to invoke globally installed npm modules. On Windows, npm can usually be found atC:\Users\username\AppData\Roaming\npm
and on Unix at/usr/local/share/npm
.
Create the App
Go to the directory where you maintain your source code, and run a command such as the following: $ cordova create hello com.example.hello HelloWorld
It may take some time for the command to complete, so be patient. Running
the command with the -d
option displays information about its progress.The first argument hello specifies a directory to be generated for your project. This directory should not already exist, Cordova will create it for you. Its
www
subdirectory houses your application's
home page, along with various resources under css
, js
, and img
,
which follow common web development file-naming conventions. The
config.xml
file contains important metadata needed to generate and
distribute the application.The second argument
com.example.hello
provides your project with a reverse domain-style identifier. This argument
is optional, but only if you also omit the third argument, since the arguments
are positional. You can edit
this value later in the config.xml
file, but do be aware that there may
be code generated outside of config.xml
using this value, such as Java
package names. The default value is io.cordova.hellocordova
, but it is
recommended that you select an appropriate value.The third argument
HelloWorld
provides the application's display title.
This argument is optional. You can edit this value later in the config.xml
file, but do be aware that there may be code generated outside of config.xml
using this value, such as Java class names. The default value is HelloCordova
,
but it is recommended that you select an appropriate value.Add Platforms
All subsequent commands need to be run within the project's directory, or any subdirectories within its scope: $ cd hello
Before you can build the project, you need to specify a set of target
platforms. Your ability to run these commands depends on whether your
machine supports each SDK, and whether you have already installed each
SDK. Run any of these from a Mac: $ cordova platform add ios
$ cordova platform add amazon-fireos
$ cordova platform add android
$ cordova platform add blackberry10
$ cordova platform add firefoxos
Run any of these from a Windows machine, where wp refers to
different versions of the Windows Phone operating system: $ cordova platform add wp7
$ cordova platform add wp8
$ cordova platform add windows8
$ cordova platform add amazon-fireos
$ cordova platform add android
$ cordova platform add blackberry10
$ cordova platform add firefoxos
Run this to check your current set of platforms: $ cordova platforms ls
(Note the platform
and platforms
commands are synonymous.)Run either of the following synonymous commands to remove a platform:
$ cordova platform remove blackberry10
$ cordova platform rm amazon-fireos
$ cordova platform rm android
Running commands to add or remove platforms affects the contents of
the project's platforms directory, where each specified platform
appears as a subdirectory. The www source directory is reproduced
within each platform's subdirectory, appearing for example in
platforms/ios/www
or platforms/android/assets/www
. Because the CLI
constantly copies over files from the source www folder, you should only
edit these files and not the ones located under the platforms subdirectories.
If you use version control software, you should add this source www folder,
along with the merges folder, to your version control system. (More information
about the merges folder can be found in the Customize Each Platform section below.)WARNING: When using the CLI to build your application, you are strongly discouraged from editing any files in the
/platforms/
folder unless you know what you are doing
or are specifically told otherwise in documentation. This is because the files in the
/platforms/
directory will be overwritten on prepare or plugin reinstallation.If you wish at this point, you can use an SDK such as Eclipse or Xcode to open the project you created. You will need to open the derivative set of assets from the
/platforms/
directory to develop with an SDK. This is because
the SDK specific metadata files are stored within the appropriate /platform/
subdirectory.
(See the Platform Guides for information on how to develop applications within each IDE.)
Use this approach if you simply want to initialize a project using the CLI and
then switch to an SDK for native work.Read on if you wish to use the cross-platform workflow approach (the CLI) for the entire development cycle.
Build the App
By default, thecordova create
script generates a skeletal web-based
application whose home page is the project's www/index.html
file.
Edit this application however you want, but any initialization should
be specified as part of the deviceready
event handler, referenced by
default from www/js/index.js
.Run the following command to iteratively build the project:
$ cordova build
This generates platform-specific code within the project's platforms
subdirectory. You can optionally limit the scope of each build to
specific platforms: $ cordova build ios
The cordova build
command is a shorthand for the following, which in
this example is also targeted to a single platform: $ cordova prepare ios
$ cordova compile ios
In this case, once you run prepare
, you can use Apple's Xcode SDK as
an alternative to modify and compile the platform-specific code that
Cordova generates within platforms/ios
. You can use the same
approachhttp://cordova.apache.org/docs/en/3.4.0guide_cli_index.md.html#The%20Command-Line%20Interface_prerequisites Test the App on an Emulator or Device
SDKs for mobile platforms often come bundled with emulators that execute a device image, so that you can launch the app from the home screen and see how it interacts with many platform features. Run a command such as the following to rebuild the app and view it within a specific platform's emulator: $ cordova emulate android
Some mobile platforms emulate a particular device by default, such as
the iPhone for iOS projects. For other platforms, you may need to
first associate a device with an emulator.Note: Emulator support is currently not available for Amazon Fire OS
(See the Platform Guides for details.) For example, you may first run the
android
command to launch the
Android SDK, then run a particular device image, which launches it
according to its default behavior:Following up with the
cordova emulate
command refreshes the emulator
image to display the latest application, which is now available for
launch from the home screen:Alternately, you can plug the handset into your computer and test the app directly:
$ cordova run android
Before running this command, you need to set up the device for
testing, following procedures that vary for each platform. In
Android and Amazon Fire OS devices, you would have to enable a USB debugging option on
the device, and perhaps add a USB driver depending on your development
environmnent.
See Platform Guides for details on each platform's requirements.Add Plugin Features
When you build and view a new project, the default application that appears doesn't do very much. You can modify the app in many ways to take advantage of standard web technologies, but for the app to communicate closely with various device-level features, you need to add plugins that provide access to core Cordova APIs.A plugin is a bit of add-on code that provides an interface to native components. You can design your own plugin interface, for example when designing a hybrid app that mixes a Cordova WebView with native components. (See Embedding WebViews and Plugin Development Guide for details.) More commonly, you would add a plugin to enable one of Cordova's basic device-level features detailed in the API Reference. A list of these plugins, including additional plugins provided by the community, can be found at plugins.cordova.io. You can use the CLI to search for plugins from this registry. For example, searching for
bar
and code
produces a single result that matches
both terms as case-insensitive substrings: $ cordova plugin search bar code
com.phonegap.plugins.barcodescanner - Scans Barcodes
Searching for only the bar
term yields and additional result: org.apache.cordova.statusbar - Cordova StatusBar Plugin
The cordova plugin add
command requires you to specify the
repository for the plugin code. Please note that when you follow the
Web Project Dev workflow and use the CLI, the CLI will take care of adding
the plugin code to the appropriate place for each platform. (If you are following the
Native Project Dev Workflow, you will have to add plugins using Plugman (guide link here),
multiple times for each platform.)Here are examples of how you might use the CLI to add features to the app:
-
Basic device information (Device API):
$ cordova plugin add org.apache.cordova.device
-
Network Connection and Battery Events:
$ cordova plugin add org.apache.cordova.network-information $ cordova plugin add org.apache.cordova.battery-status
-
Accelerometer, Compass, and Geolocation:
$ cordova plugin add org.apache.cordova.device-motion $ cordova plugin add org.apache.cordova.device-orientation $ cordova plugin add org.apache.cordova.geolocation
-
Camera, Media playback and Capture:
$ cordova plugin add org.apache.cordova.camera $ cordova plugin add org.apache.cordova.media-capture $ cordova plugin add org.apache.cordova.media
-
Access files on device or network (File API):
$ cordova plugin add org.apache.cordova.file $ cordova plugin add org.apache.cordova.file-transfer
-
Notification via dialog box or vibration:
$ cordova plugin add org.apache.cordova.dialogs $ cordova plugin add org.apache.cordova.vibration
-
Contacts:
$ cordova plugin add org.apache.cordova.contacts
-
Globalization:
$ cordova plugin add org.apache.cordova.globalization
-
Splashscreen:
$ cordova plugin add org.apache.cordova.splashscreen
-
Open new browser windows (InAppBrowser):
$ cordova plugin add org.apache.cordova.inappbrowser
-
Debug console:
$ cordova plugin add org.apache.cordova.console
plugin ls
(or plugin list
, or plugin
by itself) to view
currently installed plugins. Each displays by its identifier: $ cordova plugin ls # or 'plugin list'
[ 'org.apache.cordova.console' ]
To remove a plugin, refer to it by the same identifier that appears in
the listing. For example, here is how you would remove support for a
debug console from a release version: $ cordova plugin rm org.apache.cordova.console
$ cordova plugin remove org.apache.cordova.console # same
You can batch-remove or add plugins by specifying more than one
argument for each command: $ cordova plugin add org.apache.cordova.console org.apache.cordova.device
Advanced Plugin Options
When adding a plugin, several options allow you to specify from where to fetch the plugin. The examples above use a well-knownregistry.cordova.io
registry, and the plugin is specified by the
id
: $ cordova plugin add org.apache.cordova.console
The id
may also include the plugin's version number, appended after
an @
character. The latest
version is an alias for the most recent
version. For example: $ cordova plugin add org.apache.cordova.console@latest
$ cordova plugin add org.apache.cordova.console@0.2.1
If the plugin is not registered at registry.cordova.io
but is located in
another git repository, you can specify an alternate URL: $ cordova plugin add https://github.com/apache/cordova-plugin-console.git
The git example above fetches the plugin from the end of the master
branch, but an alternate git-ref such as a tag or branch can be
appended after a #
character: $ cordova plugin add https://github.com/apache/cordova-plugin-console.git#r0.2.0
If the plugin (and its plugin.xml
file) is in a subdirectory within
the git repo, you can specify it with a :
character. Note that the
#
character is still needed: $ cordova plugin add https://github.com/someone/aplugin.git#:/my/sub/dir
You can also combine both the git-ref and the subdirectory: $ cordova plugin add https://github.com/someone/aplugin.git#r0.0.1:/my/sub/dir
Alternately, specify a local path to the plugin directory that
contains the plugin.xml
file: $ cordova plugin add ../my_plugin_dir
Using merges to Customize Each Platform
While Cordova allows you to easily deploy an app for many different platforms, sometimes you need to add customizations. In that case, you don't want to modify the source files in variouswww
directories
within the top-level platforms
directory, because they're regularly
replaced with the top-level www
directory's cross-platform source.Instead, the top-level
merges
directory offers a place to specify
assets to deploy on specific platforms. Each platform-specific
subdirectory within merges
mirrors the directory structure of the
www
source tree, allowing you to override or add files as needed.
For example, here is how you might uses merges
to boost the default
font size for Android and Amazon Fire OS devices:-
Edit the
www/index.html
file, adding a link to an additional CSS file,overrides.css
in this case:
<link rel="stylesheet" type="text/css" href="css/overrides.css" />
- Optionally create an empty
www/css/overrides.css
file, which would apply for all non-Android builds, preventing a missing-file error. -
Create a
css
subdirectory withinmerges/android
, then add a correspondingoverrides.css
file. Specify CSS that overrides the 12-point default font size specified withinwww/css/index.css
, for example:
body { font-size:14px; }
You can also use
merges
to add files not present in the original
www
directory. For example, an app can incorporate a back button
graphic into the iOS interface, stored in
merges/ios/img/back_button.png
, while the Android version can
instead capture backbutton
events from the corresponding hardware
button.Help Commands
Cordova features a couple of global commands, which may help you if you get stuck or experience a problem. Thehelp
command displays
all available Cordova commands and their syntax:$ cordova help
$ cordova # same
The info
command produces a listing of potentially useful details,
such as currently installed platforms and plugins, SDK versions for
each platform, and versions of the CLI and node.js
:$ cordova info
It both presents the information to screen and captures the output in
a local info.txt
file.NOTE: Currently, only details on iOS and Android platforms are available.
Updating Cordova and Your Project
After installing thecordova
utility, you can always update it to
the latest version by running the following command: $ sudo npm update -g cordova
Use this syntax to install a specific version: $ sudo npm install -g cordova@3.1.0-0.2.0
Run cordova -v
to see which version is currently running. Run the npm
info
command for a longer listing that includes the current version
along with other available version numbers: $ npm info cordova
Cordova 3.0 is the first version to support the command-line interface
described in this section. If you are updating from a version prior to
3.0, you need to create a new project as described above, then copy
the older application's assets into the top-level www
directory.
Where applicable, further details about upgrading to 3.0 are available
in the Platform Guides. Once you upgrade to the cordova
command-line interface and use npm update
to stay current, the more
time-consuming procedures described there are no longer relevant.Cordova 3.0+ may still require various changes to project-level directory structures and other dependencies. After you run the
npm
command above to update Cordova itself, you may need to
ensure your project's resources conform to the latest version's
requirements. Run a command such as the following for each platform
you're building: $ cordova platform update android
$ cordova platform update ios
...etc.
Original link:
http://cordova.apache.org/docs/en/3.4.0/guide_cli_index.md.html#The%20Command-Line%20Interface_prerequisites
Subscribe to:
Posts (Atom)